Leetcode longest-substring-without-repeating-characters(java實現)
阿新 • • 發佈:2018-12-09
第一種解題方法
題目是求最長無重複子字串
1.採用定義一個256位大小的整型陣列來代替HashMap,保證了無重複性,256位長度是因ASCII表共能表示256個字元來記錄所有字元。
2.定義標記無重字串最左邊的位置和最終結果長度的int整型變數,left和res,遍歷整個字串:
第一種情況:一直遍歷沒有遇到無重子串,則返回結果等於i - left +1,i為無重子串最右邊的位置;
第二種情況:在遍歷過程中,出現了遇見重複字元的情況,此時返回重複字元第一次定義的位置,也就是此時雜湊表裡該字元的對應值小於left,此時res返回max(res,i-left)的結果時。返回的仍是上次遍歷得到的res值,因為此時i-left<res;
public int longest_substr(String s){
int [] m = new int [256];
Arrays.fill(m, -1);
int res = 0;
int left =-1;
for (int i = 0;i<s.length();i++){
left = Math.max(left, m[s.charAt(i)]);
m[s.charAt(i)] = i;
res = Math.max(res, i-left);
}
return res;
第二種方法
採用hashset,與第一種類似,相比第一種方法,它是遍歷到到重複字元就將第一次遇到的該字元從hashset中移除。
public int lengthOfLongestSubstring(String s) { int n = s.length(),left = 0,right = 0,res = 0; HashSet<Character> h = new HashSet<Character>(); while(right < n){ if (!h.contains(s.charAt(right))){ h.add(s.charAt(right)); right++; res = Math.max(res, h.size()); }else{ h.remove(s.charAt(left)); left++; } } return res; }