From f520b1dc172dafbc4361c48e3df22b8da399a2c3 Mon Sep 17 00:00:00 2001 From: Wang ChaoLan <68094392+Junior-W@users.noreply.github.com> Date: Thu, 9 Nov 2023 17:20:12 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20kama55.=E5=8F=B3=E6=97=8B?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama55.右旋字符串.md | 62 ++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/problems/kama55.右旋字符串.md b/problems/kama55.右旋字符串.md index afd29d73..f3841930 100644 --- a/problems/kama55.右旋字符串.md +++ b/problems/kama55.右旋字符串.md @@ -145,8 +145,70 @@ int main() { ## 其他语言版本 ### Java: +```Java +// 版本一 +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = Integer.parseInt(in.nextLine()); + String s = in.nextLine(); + + int len = s.length(); //获取字符串长度 + char[] chars = s.toCharArray(); + reverseString(chars, 0, len - 1); //反转整个字符串 + reverseString(chars, 0, n - 1); //反转前一段字符串,此时的字符串首尾尾是0,n - 1 + reverseString(chars, n, len - 1); //反转后一段字符串,此时的字符串首尾尾是n,len - 1 + + System.out.println(chars); + + } + + public static void reverseString(char[] ch, int start, int end) { + //异或法反转字符串,参照题目 344.反转字符串的解释 + while (start < end) { + ch[start] ^= ch[end]; + ch[end] ^= ch[start]; + ch[start] ^= ch[end]; + start++; + end--; + } + } +} +// 版本二 +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = Integer.parseInt(in.nextLine()); + String s = in.nextLine(); + + int len = s.length(); //获取字符串长度 + char[] chars = s.toCharArray(); + reverseString(chars, 0, len - n - 1); //反转前一段字符串,此时的字符串首尾是0,len - n - 1 + reverseString(chars, len - n, len - 1); //反转后一段字符串,此时的字符串首尾是len - n,len - 1 + reverseString(chars, 0, len - 1); //反转整个字符串 + + System.out.println(chars); + + } + + public static void reverseString(char[] ch, int start, int end) { + //异或法反转字符串,参照题目 344.反转字符串的解释 + while (start < end) { + ch[start] ^= ch[end]; + ch[end] ^= ch[start]; + ch[start] ^= ch[end]; + start++; + end--; + } + } +} +``` ### Python: