原题:Longest Substring Without Repeating Characters
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.
解答:
C++版本
<span style="font-size:24px;"><span style="font-family:Times New Roman;">int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}</span></span>
Java版本
<span style="font-size:24px;"><span style="font-family:Times New Roman;"> public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int i=0, j=0; i<s.length(); ++i){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-j+1);
}
return max;
}</span></span>
注意:
1、map.put(s.charAt(i),i),当s.charAt(i)重复时,i值会得到更新,如map中已经存在
(e,2),当执行map.put(e,3)时,原来的(e,2)变为(e,3)。
2、j = Math.max(j,map.get(s.charAt(i))+1),比较重复的位置,很重要,如果位置在j之前,则不需要更新j。