给定两个字符串,A和B
A的旋转操作就是将A最左边的字符移动到最右边
例如:若A='abcde',在移动一次后结果就是'bcdea'。
如果在若干次调整操作之后,A能变成B就返回true。如果不能匹配成功,则返回false。
注意:字符串不可以修改
套路:如果以后我们看到要修改字符串的内容,有以下两个办法
1.使用substring进行截取,将左侧的字符截取出来拼接到右侧去
2.可以把字符串变成一个字符数组,然后调整字符数组里面的数据,最后把字符数组变成字符串
方法一:
//调整字符串
public class Test{
public static void main(String args[]) {
//1.定义两个字符串
String strA="abcde";
String strB="cdeab";
//2.调用方法并且比较->将字符串旋转(abcde->bcdea->cdeab)
boolean result=checkstr(strA,strB);
//调整次数是有限的,和字符串长度一样
//3.输出
System.out.println("是否能将A转换成B:"+result);
}
//作用:旋转字符串,把左端的字符移到右端去
//形参:旋转前的字符串
//返回值:旋转后的字符串
public static String rotate(String str) {
//方法一:截取字符串
String first=str.substring(0,1);//获取第一个字符
char first1=str.charAt(0);//如果只获取一次,也可以使用charAt
String end=str.substring(1);//截取剩余的字符串,必须用substring
return end+first;
}
//循环旋转并比较
public static boolean checkstr(String strA,String strB) {
for(int i=0;i<strA.length();i++) {
strA=rotate(strA);
if(strA.equals(strB)) {
return true;
}
}
return false;
}
}
方法二:
public class Test{
public static void main(String args[]) {
String strA="abcde";
String strB="adeab";
boolean result=checkstr(strA,strB);
System.out.println("字符串是否可以调整"+result);
}
public static String rotate(String str) {
//将字符串变成数组
char[] arr=str.toCharArray();//"ABC"->['A','B','C']
char first=arr[0];//拿到0索引上的字符
//把剩余的字符依次往前一个位置
for(int i=1;i<arr.length;i++) {
arr[i-1]=arr[i];
}
// 把原来0索引的字符放在最后
arr[arr.length-1]=first;
String result=new String(arr);
return result;
}
public static boolean checkstr(String strA,String strB) {
for(int i=0;i<strA.length();i++) {
strA=rotate(strA);
if(strA.equals(strB)) {
return true;
}
}
return false;
}
}