挑战刷leetcode第三天( 无重复字符的最长子串),你看我行吗?

61 阅读1分钟

java版本

   public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        int left = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                left = Math.max(left, map.get(s.charAt(i)) + 1);
            }
            res = Math.max(res, i - left + 1);
            map.put(s.charAt(i), i);
        }
        return res;
    }

C++版本

 int lengthOfLongestSubstring(string s) {
        unordered_set<char> set;
        int res = 0;
        int left = 0;
        for (int i = 0; i < s.size(); i++) {
            while (set.find(s[i]) != set.end()) {
                set.erase(s[left]); // 修正了这里的拼写错误
                left++;
            }
            res = max(res, i - left + 1);
            set.insert(s[i]);
        }
        return res;
    }

总结

核心就是使用滑动时间窗口,遇到重复的元素向右移动,每次取窗口内的最大值

打卡完成,继续坚持!!!希望友友们监督哈