leetcode 3.无重复字符的最长子串

发布时间 2024-01-01 12:06:57作者: 米乡卷炸粉

leetcode

第三题:无重复字符的最长子串

自己写的:

第一想法:滑动窗口,用两个指针指向窗口的左右边界,用一个HashSet存储窗口内已有的值。另写一个find_first_temp方法用于出现重复字符时寻找新的左边界,左边界更新时也要更新set,将新左边界之前的元素删掉。

public int lengthOfLongestSubstring(String s) {
        HashSet<Character> re = new HashSet<>();
        int left = 0;
        int right = 0;
        int Max = 0;
        for (int i = 0;i<s.length() ;i++){
            char temp = s.charAt(i);
            if (!re.contains(temp)){
                re.add(s.charAt(i));
                right++;
            }
            else {
                int temp_left = left;
                left = find_first_temp(s,temp,left);
                for (int j = temp_left;j<left;j++){
                    re.remove(s.charAt(j));
                }
                re.add(temp);
                right++;
            }
            Max = Math.max(Max,right - left);
        }
        return Max;
    }

    public int find_first_temp(String s,char temp, int left){
        for (int i = left; i<s.length() ;i++){
            if (s.charAt(i) == temp){
                return i+1;
            }
        }
        return 0;
    }

官方答案的:

public int lengthOfLongestSubstring(String s) {
        // 哈希集合,记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格,移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }

区别:我是移动右指针,答案移动左指针,所用时间内存相差不多,都是遍历一次+set,但答案更为简洁。