欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode3: 无重复字符的最长字串

程序员文章站 2022-04-04 09:59:19
...

题目

leetcode3: 无重复字符的最长字串

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        int maxLen = 1;
        int curLen = 0;
        Map<Character, Integer> map = new HashMap<>();  //记录当前子串中每个字符出现的位置
        int i = 0;
        int n = s.length();
        char curChar;
        int lastIndex = -1;  //重复的字符上一次出现的位置
        while (i < n) {
            curChar = s.charAt(i);
            if (!map.containsKey(curChar) || map.get(curChar) < lastIndex) {
                curLen++;
                map.put(curChar, i);
            } else {
                lastIndex = map.get(curChar);
                maxLen = Math.max(curLen, maxLen);
                curLen = i - lastIndex;
                map.put(curChar, i);
            }
            i++;
        }
        maxLen = Math.max(curLen, maxLen);
        return maxLen;
    }
}