使用 StringBuilder 而不是字符数组旋转字符串

Rotating a String with StringBuilder instead of a character array

旨在通过旋转直到匹配来检查一个字符串是否是另一个字符串的旋转。

尝试使用 StringBuilder 而不是 char[ ] 来旋转所述字符串,因为它更有效,但我无法确定为什么字符串只旋转一次,而不是 a.length()- 1次。

public static void main(String[] args) {
    
    String a = "erbottlewat";
    String b = "waterbottle";
    
    System.out.println(isSubstring(a,b));
    
}


    public static boolean isSubstring(String a, String b) {
    
    StringBuilder strbdr = new StringBuilder(a); // can pick either string. if one ends up matching the other one, we know it is a rotation
    
    for(int i = 0; i < a.length()-1; i++) { // this is the number of times the program will run
        
        char temp = a.charAt(0);
        
        for(int j = 0; j < a.length()-1; j++) {
            strbdr.setCharAt(j, a.charAt(j+1)); // tried to use a stringbuilder because i read it was the most efficient way.
        }
        
        strbdr.setCharAt(a.length()-1, temp);
        
        System.out.println(strbdr.toString());
        
        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;
    
}

}

我的错误是索引 String a(从未更改过)以用 StringBuilder 替换元素。通过将 strbdr.setCharAt(j, a.charAt(j+1)); 替换为 strbdr.setCharAt(j, strbdr.charAt(j+1));,我能够保存更改并正确旋转字符串。

解决方案:

public static void main(String[] args) {
    
    String a = "erbottlewat";
    String b = "waterbottle";
    
    System.out.println(isSubstring(a,b));
    
}

public static boolean isSubstring(String a, String b) {
    
    StringBuilder strbdr = new StringBuilder(a);
    
    for(int i = 0; i < a.length()-1; i++) {
        
        char temp = strbdr.charAt(0);
        
        for(int j = 0; j < a.length()-1; j++) {
            strbdr.setCharAt(j, strbdr.charAt(j+1));
        }
        
        strbdr.setCharAt(a.length()-1, temp);
        
        System.out.println(strbdr.toString());
        
        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;
    
}