【leetcode刷题笔记】3. 无重复字符的最长子串

链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/

 

这题主要就是一个滑动窗口。思路马上能想到,但是各种边界条件想明白比较麻烦。

看了答案后简化版的代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int endIndex = 0;
        int maxLength = 0;
        Set<Character> existCharSet = new HashSet<>();
        for (int startIndex = 0; startIndex < s.length(); startIndex++) {
            if (startIndex != 0) {
                existCharSet.remove(s.charAt(startIndex - 1));
            }
            while (!existCharSet.contains(s.charAt(endIndex))) {
                existCharSet.add(s.charAt(endIndex));
                endIndex++;
                if (endIndex == s.length()) {
                    break;
                }
            }
            maxLength = Math.max(maxLength, endIndex - startIndex);
            if (endIndex == s.length()) {
                break;
            }
        }

        return maxLength;
    }
}

 

posted on 2021-01-10 23:05  FunBing  阅读(38)  评论(0编辑  收藏  举报

导航