【发布时间】:2022-01-25 19:02:01
【问题描述】:
旨在通过旋转直到匹配来检查一个字符串是否是另一个字符串的旋转。
尝试使用 StringBuilder 来旋转所述 String 而不是 char[ ],因为它更有效,但我无法确定为什么 String 只旋转一次,而不是 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;
}
}
【问题讨论】:
-
我用 char[] 重新解决了这个问题,它有更多的内部循环,我相信这会将复杂性增加到 O(n^3),但我会在问题下方添加蛮力解决方案!此外,您能否通过 a.charAt() 不使用 StringBuilder 来扩展您的意思?
-
知道了!我只需要在每次更改后通过将 String a 设置为 StringBuilder 来存储更改! for(int j = 0; j
-
@user16320675 完成!发布更新的解决方案。
标签: java string rotation stringbuilder