2 回答

TA貢獻1802條經驗 獲得超5個贊
String one = "david";
String two = "vidda";
one.concat(one).indexOf(two)
會工作,不是嗎?

TA貢獻1830條經驗 獲得超3個贊
我不知道我的方法是否足夠快......但它的運行時間是字符串的長度在O(n)哪里。n
這種方法只有在它是可解的并且兩個字符串具有相同長度的情況下才有效:
public static void main(String[] args) {
String string1 = "david";
String string2 = "avidd";
char[] a = string1.toCharArray();
char[] b = string2.toCharArray();
int pointer = a.length-1;
int off = 0;
int current = 0;
for (int i = b.length-1; i >= 0; i--) {
if (b[i] == a[pointer]) { //found a match
current++; //our current match is one higher
pointer--; //pointer of string1 goes one back
} else if (current != 0) { //no match anymore and we have had a match
i ++; //we have to recalculate the actual position in the next step of the loop
off += current; //we have to rotate `current` times more
current = 0; //reset current match
pointer = a.length-1; //reset pointer
} else { //no match and we didn't have had a match the last time
off ++; //we have to rotate one more time
}
}
System.out.println("Rotate: " + off);
}
基本上它從兩個字符串的末尾開始并回到開頭,直到它不再有任何差異。如果它在任何時候確實有差異,它會將當前計數器添加off到string1.
我的算法在完成旋轉后不檢查字符串是否相同。off
添加回答
舉報