Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
題目分析:給出一個字符串,求出它沒有重復字符的最長長度。我們當然可以用兩重循環,找出最長無重復字符的長度。這種顯然不是我們期望的。我們可以用一個map來實現,map保存的key-val值為string中字符的值以及它上一次出現的位置,index表示沒有重復字符字符串的首字符位置,i代表沒有重復字符字符串的最右位置。每次遍歷到i時,如果map不包含s.charAt(i),則計算長度i-len+1,否則,更新index位置。然后再計算長度。一次遍歷之后就可以得到結果。
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0)
return 0;
if (s.length() == 1)
return 1;
HashMap<Character, Integer> map = new HashMap<>();
int result = 0;
int index = 0;
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
index = Math.max(index, 1 + map.get(s.charAt(i)));
}
int len = i - index + 1;
map.put(s.charAt(i), i);
result = Math.max(len, result);
}
return result;
}