旨在通過旋轉它直到匹配來檢查一個字串是否是另一個字串的旋轉。
嘗試使用 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;
}
}
uj5u.com熱心網友回復:
我的錯誤是索引 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396868.html
