字符串旋转 — Java

it2022-05-05  126

给定两字符串A和B,如果能将A从中间某个位置分割为左右两部分字符串(都不为空串),并将左边的字符串移动到右边字符串后面组成新的字符串可以变为字符串B时返回true。 例如:如果A=‘youzan’,B=‘zanyou’,A按‘you’‘zan’切割换位后得到‘zanyou’和B相同返回true。 思路:每次将A字符串首字母向后移动一位,将新形成的字符串与B进行比较。

import java.util.Scanner; public class reverseCharacter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入字符串,以;作为分割A和B的标志"); String str = sc.nextLine(); String[] m = str.split(";"); String A = m[0]; String B = m[1]; System.out.println(reverseChararcter(A, B)); } public static boolean reverseChararcter(String A,String B) { if(A == B) { return true; } char[] arrA = A.toCharArray(); char[] arrB = B.toCharArray(); if(arrA.length == arrB.length) { int len = arrA.length; int count = 0; //count记录循环次数,当count = n-1时退出循环 while(!judge(arrA, arrB) && count < len-1) { char temp = arrA[0]; for(int j = 0; j < len-1; j++) { arrA[j] = arrA[j+1]; } arrA[len-1] = temp; count++; //将每次变换后的A字符串打印出来 for (int k = 0; k < len; k++) { char c = arrA[k]; System.out.print(c); } System.out.println(); } if(count < len-1) { return true; }else { return false; } }else { return false; } } //判断A.B是否已经相同 public static boolean judge(char[] arrA,char[] arrB) { for(int i = 0; i < arrA.length; i++) { if(arrA[i] != arrB[i]) { return false; } } return true; } }

最新回复(0)