Skip to content

Latest commit

 

History

History
26 lines (26 loc) · 1014 Bytes

3.md

File metadata and controls

26 lines (26 loc) · 1014 Bytes

#3. Longest Substring Without Repeating Characters 题目链接

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLength = 0;
        int afterSameIndex = 0;
        HashMap<Character, Integer> hm = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            /*
             * 如果已经存在,那么将下标取出来,并且加一
             * 从相同的下标后面再次查找最大的子串
             * 如果再次遇到相同的字母,那么比较这两个字母的先后顺序
             * 以位置靠后的字母下标为准
             */
            if (hm.containsKey(c)) {
                afterSameIndex = Math.max(hm.get(c) + 1, afterSameIndex);
            }
            hm.put(c, i);
            maxLength = Math.max(maxLength, i - afterSameIndex + 1);
        }
        return maxLength;
    }
}