我不知道我的方法是否足够快......但它的运行时间是字符串的长度在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