1 package com.itheima.test; 2 3 public class Test2Case1 { 4 public static void main(String[] args) { 5 /*给定两个字符串 6 A 旋转,将A最左边字符移动至最右边 7 abcde->bcdea 8 若干次调整,A变成B,返回True*/ 9 //定义两个字符串 10 String str1 = "abcde"; 11 String str2 = "chb"; 12 //旋转 13 String rotate = rotate(str1); 14 System.out.println(rotate); 15 boolean check = check(str1, str2); 16 System.out.println(check); 17 } 18 19 public static boolean check(String strA,String strB){ 20 for (int i = 0; i < strA.length(); i++) { 21 strA = rotate(strA); //关键步骤 22 if(strA.equals(strB)){ 23 return true; 24 } 25 } 26 return false; 27 } 28 //subString截取 29 //旋转字符串类型,返回值还是字符串 30 public static String rotate(String str){ 31 //获取第一个字符 32 char first = str.charAt(0); 33 //截取掉第一个,后面全部变成字符串 34 String end = str.substring(1); 35 return end+first; 36 } 37 }
1 package com.itheima.test; 2 3 public class Test2Case2 { 4 public static void main(String[] args) { 5 /*给定两个字符串 6 A 旋转,将A最左边字符移动至最右边 7 abcde->bcdea 8 若干次调整,A变成B,返回True*/ 9 //定义两个字符串 10 String str1 = "abcde"; 11 String str2 = "chb"; 12 //旋转 13 //String rotate = rotate(str1); 14 //System.out.println(rotate); 15 boolean result = check(str1, str2); 16 System.out.println(result); 17 } 18 19 public static boolean check(String strA,String strB){ 20 for (int i = 0; i < strA.length(); i++) { 21 strA = rotate(strA); //关键步骤 22 if(strA.equals(strB)){ 23 return true; 24 } 25 } 26 return false; 27 } 28 29 //把字符串先变成一个字符数组,然后调整字符数组里面数据,最后把字符数组变成字符串 30 public static String rotate(String str){ 31 //将字符串变成字符数组的方法 "ABC" ->['A''B''C'] ['B''C''A'] 32 char[] arr = str.toCharArray(); 33 //拿到零索引上的字符 34 char first = arr[0]; 35 //剩余字符依次往前挪 36 for (int i = 1; i < arr.length; i++) { 37 arr[i-1] = arr[i]; 38 } 39 //0索引放在最后 40 arr[arr.length-1] = first; 41 //利用字符数组创建一个字符串对象 42 String result = new String(arr); 43 return result; 44 } 45 }
标签:arr,rotate,String,bcdea,abcde,字符串,strA,public From: https://www.cnblogs.com/Wang0626/p/17233351.html