原本遇到判斷字符串中是否含有重復元素的問題總是使用for循環遍歷進行判斷,這一方法則需要O(n3)的時間復雜度,如果本身方法處於幾個循環中,就會指數倍增加時間復雜度。類似於如下代碼:
String[] a = s.split("");
int max = 1;
for(int i = 0; i < a.length; i++){
String[] b = new String[a.length - i];
b[0] = a[i];
int permax = 1;
for(int j = i + 1, k = 1; k < b.length && j < a.length; j++, k++){
boolean repeat = false;
for(String c: b){
if(a[j].equals(c)){
repeat = true;
}
}
if(repeat == false){
b[k] = a[j];
permax++;
if(permax > max){
max = permax;
}
}
else
break;
}
}
一種更快的判斷方法則是使用HashMap或Hashset,利用HashMap中的containsValue()或Hashset中的contains()方法,可以直接判斷出字符串中是否有重復的元素,需要的時間復雜度為O(n2),我使用的是HashMap,代碼如下:
String[] a = s.split("");
HashMap<Integer, String> map = new HashMap<>();
int max = 1;
for(int i = 0; i < a.length; i++){
map.clear();
map.put(i, a[i]);
int permax = 1;
for(int j = i + 1 ;j < a.length; j++){
if(!map.containsValue(a[j])){
map.put(j, a[j]);
permax++;
if(permax > max){
max = permax;
}
}
else
break;
}
}
可以看見,代碼中只使用了兩層for循環,可以明顯加快代碼執行時間,要記住每次循環后要使用clear()方法將HashMap中所有映射刪除。
