Leetcode 3
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.
解题 : 用hash,key是字符,value是上一次出现的位置,从头到位遍历字符串,如果字符出现过,我们就把start指针移到当前字符,期间不断的比最大子串。
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0, j = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
//map contains key, move start to the position last character appears
j = Math.max(j, map.get(c)+1);
}
//keep updating the position of character last appears
map.put(c, i);
ans = Math.max(ans, i-j+1);
}
return ans;
}
}