题目描述
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
思路
维护一个字典保存每个字符上次出现的位置,一个变量保存最大子串的起始点。
代码与注释
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if (n==0) return 0;
HashMap<Character, Integer> map = new HashMap<>();
int ans = 0;
for (int i = 0, j = 0; i < n; i++) {
if (map.containsKey(s.charAt(i)))
j = Math.max(j, map.get(s.charAt(i))+1);
map.put(s.charAt(i), i);
ans = Math.max(i-j+1, ans);
}
return ans;
}
}