zoukankan      html  css  js  c++  java
  • 双指针算法

    双指针算法

    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;
        }
    }
    
  • 相关阅读:
    Flutter
    Flutter
    项目冲刺——第二天
    练习三:用例图
    项目冲刺——第一天
    作业六:团队项目冲刺前期准备
    作业四:软件案例分析
    作业五:需求规格说明书
    【非作业部分】队内暂时安排
    第二次练习——团队展示
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13289984.html
Copyright © 2011-2022 走看看