剑指 Offer 48. 最长不含重复字符的子字符串

126 阅读1分钟
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) return s.length();
        HashMap<Character, Integer> map = new HashMap<>();
        int left = 0, right = 0, ans = 0;
        while (right < s.length()) {
            if (map.containsKey(s.charAt(right))) {
                int index = map.get(s.charAt(right));
                if (index >= left) {
                    left = index + 1;
                }
            }
            map.put(s.charAt(right), right);
            ans = Math.max(ans, right - left + 1);
            right++;
        }
        return ans;
    }
}