每一天一道算法题训练,努力打开编程思维,才能进大厂光明正大的泡心仪的小姐姐!!(手动捂脸)
题目
/**
* 给定字符创A和B
* 旋转字符串A,就是把最左边的移动到最右边
* 比如A=‘abcde’,在移动一次之后结果就是bcdea
* 如果若干次之后,A能变成B,返回true,否则返回false
**/
代码实现
- 【js代码】
let strA = "abcde";let strB = "cdeab";const result = check(strA,strB)console.log("🚀 ~ result:", result)function check(strA,strB){if(!strA || !strB || strA.length != strB.length) return falsefor (let index = 0; index < strA.length; index++) {strA = rotate(strA)if(strA == strB){return true}}return false}function rotate(strA){if(!strA) return ''let start = strA[0];let end = strA.substring(1)return end + start}
运行结果
- 【java代码】
public class stringdemo05 {public static void main(String[] args) {//String strA = "abcde";String strB = "cdeab";boolean res = check(strA,strB);System.out.printf("🚀 ~ result:第一个字符串是%s,第二个字符串是%s",strA,strB);System.out.print(" 返回结果是" + res);}public static boolean check(String strA,String strB){for (int i = 0; i < strA.length(); i++) {strA = rotate(strA);if(strA.equals(strB)){return true;}}return false;}public static String rotate(String str){char start = str.charAt(0);String end = str.substring(1);return end + start;}
}
这样就实现了需求效果!!