Given a string, find the length of the longest substring without
repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For
"bbbbb" the longest substring is "b", with the length of 1.
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int maxLength = 0;
int start = 0;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
Integer p = map.get(c);
if(p==null || p.intValue()<start) {
map.put(c, i);
maxLength = Math.max(i-start+1, maxLength);
} else {
start = p.intValue()+1;
map.put(c, i);
}
}
return maxLength;
}
}
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int ans = 0;
int last = -1;
for(int i=0;i<s.size();i++) {
char c = s[i];
if(hash.find(c)!=hash.end()) {
last = max(last, hash[c]);
}
ans = max(ans, i-last);
hash[c] = i;
}
return ans;
}
};
没有评论:
发表评论