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

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

思路一:双指针+HashSet
官方题解

class Solution {
    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;
    }
}

思路二:用一个数组存储重复字符上一次出现的位置,以上次出现位置+1作为新的起始位置

public class Problem3 {
    public int lengthOfLongestSubstring(String s) {
        int[] pos=new int[128];
        int n=s.length();
        int start=0;
        int ans=0;
        for (int i = 0; i < n; i++) {
            int index=s.charAt(i);
            start=Math.max(start,pos[index]);
            ans=Math.max(ans,i-start+1);
            pos[index]=i+1;
        }
        return ans;
    }
}

posted @ 2021-02-02 10:20  withwind777  阅读(47)  评论(0)    收藏  举报