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.
題目分析:給出一個(gè)字符串的妖,求出它沒有重復(fù)字符的最長長度。我們當(dāng)然可以用兩重循環(huán)叫胖,找出最長無重復(fù)字符的長度即舌。這種顯然不是我們期望的塔淤。我們可以用一個(gè)map來實(shí)現(xiàn),map保存的key-val值為string中字符的值以及它上一次出現(xiàn)的位置养筒,index表示沒有重復(fù)字符字符串的首字符位置,i代表沒有重復(fù)字符字符串的最右位置帜消。每次遍歷到i時(shí),如果map不包含s.charAt(i)设褐,則計(jì)算長度i-len+1,否則颠蕴,更新index位置。然后再計(jì)算長度助析。一次遍歷之后就可以得到結(jié)果犀被。
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;
}