双指针算法

双指针算法

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

while()是非法的,在外更新答案

class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] c = s.toCharArray();
        int n = c.length;
        int[] cnt = new int[128];
        int res = 0;
        for(int i=0, j=0; j < n; j++) {
            cnt[c[j]]++;
            while(i <= j && cnt[c[j]] > 1) cnt[c[i++]]--;
            res = Math.max(res, j-i+1);
        }
        return res;
    }
}

LeetCode 76. 最小覆盖子串

注意while()中是合法,在此更新答案。

class Solution {
    boolean isEq(int[] cnt1, int[] cnt2) {
        for(int i=0; i < 128; i++) 
            if(cnt2[i] != 0 && cnt2[i] > cnt1[i])
                return false;
        return true;
    }
    public String minWindow(String s, String t) {
        if(t.equals("")) return "";
        char[] s1 = s.toCharArray();
        char[] t1 = t.toCharArray();
        int n = s1.length, m = t1.length;
        int[] cnt1 = new int[128];
        int[] cnt2 = new int[128];
        for(int i=0; i < m; i++) cnt2[t1[i]] ++;
        String res = "";
        for(int i=0, j=0; j < n; j++) {
            cnt1[s1[j]]++;
            while(i <= j && isEq(cnt1, cnt2)) {
                //System.out.println(i+","+j);
                if((res.equals("") || res.length() > j-i+1)) 
                    res = s.substring(i, j+1);
                cnt1[s1[i++]]--;
            }
        }
        return res;
    }
}
posted @ 2020-07-12 21:26  li修远  阅读(97)  评论(0编辑  收藏  举报