我已经写了下面$ C $下检测第一个字符串中重复的字符。
I have written below code for detecting first duplicate character in a string.
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;
}
我需要两件事情帮助:
I need help on two things:
什么是该算法的最坏情况下的复杂性? - 我的理解是O(n)。 是否做到这一点的最好方法是什么?有人可以提供更好的解决方案(如果有的话)?谢谢, NN
正如其他人所说,你的算法是O(n ^ 2)。下面是一个O(n)的算法,因为HashSet的#添加运行在固定的时间(在哈希函数将正确的元素桶中) - 请注意,我原来的大小HashSet的最大大小,以避免调整/换汤不换药:
As mentioned by others, your algorithm is O(n^2). Here is an O(N) algorithm, because HashSet#add runs in constant time ( the hash function disperses the elements properly among the buckets) - Note that I originally size the hashset to the maximum size to avoid resizing/rehashing:
public static int findDuplicate(String s) {
char[] chars = s.toCharArray();
Set<Character> uniqueChars = new HashSet<Character> (chars.length, 1);
for (int i = 0; i < chars.length; i++) {
if (!uniqueChars.add(chars[i])) return i;
}
return -1;
}
注:此方法返回的第一个重复的指标(即是previous字符的副本的第一个字符的索引)。要返回字符的第一次亮相的索引,你需要存储索引在地图&LT;性格,整数GT;
(地图#放
也是O(1)在这种情况下):
Note: this returns the index of the first duplicate (i.e. the index of the first character that is a duplicate of a previous character). To return the index of the first appearance of that character, you would need to store the indices in a Map<Character, Integer>
(Map#put
is also O(1) in this case):
public static int findDuplicate(String s) {
char[] chars = s.toCharArray();
Map<Character, Integer> uniqueChars = new HashMap<Character, Integer> (chars.length, 1);
for (int i = 0; i < chars.length; i++) {
Integer previousIndex = uniqueChars.put(chars[i], i);
if (previousIndex != null) {
return previousIndex;
}
}
return -1;
}