我写了下面的代码来检测字符串中的第一个重复字符.
public static int detectDuplicate(String source) {
boolean found = false;
int index = -1;
final long start = System.currentTimeMillis();
final int length = source.length();
for(int outerIndex = 0; outerIndex < length && !found; outerIndex++) {
boolean shiftPointer = false;
for(int innerIndex = outerIndex + 1; innerIndex < length && !shiftPointer; innerIndex++ ) {
if ( source.charAt(outerIndex) == source.charAt(innerIndex)) {
found = true;
index = outerIndex;
} else {
shiftPointer = true;
}
}
}
System.out.println("Time taken --> " + (System.currentTimeMillis() - start) + " ms. for string of length --> " + source.length());
return index;
}
我需要两件事的帮助:
>此算法的最坏情况复杂度是多少? – 我的理解是O(n).
>这是最好的方法吗?有人可以提供更好的解决方案(如果有的话)吗?
谢谢,
NN