首页 > 其他 > 详细

leetcode 395. Longest Substring with At Least K Repeating Characters(高质量题)

时间:2019-04-27 16:40:04      阅读:136      评论:0      收藏:0      [点我收藏+]

只能说还是太菜,抄的网上大神的做法:
idea:

  1. mask 的每一位代表该位字母够不够k次,够k次为0,不够为1
  2. 对于每一位将其视为起点,遍历至末尾,找到其最大满足子串T的下标max_idx,之后从max_idx+1开始遍历。

代码如下:

public int longestSubstring(String s, int k) {
        if (k == 1) return s.length();
        int res = 0, i = 0, n = s.length();
        while (i + k <= n){
            int[] m = new int[26];
            int mask = 0, max_idx = i;
            for (int j = i; j < n; j ++){
                int t = s.charAt(j) - 'a';
                m[t]++;
                if (m[t] < k) mask |= (1 << t);
                else mask &= (~(1 << t));
                if (mask == 0){
                    res = Math.max(res, j - i + 1);
                    max_idx = j;
                }
            }
            i = max_idx + 1;
        }
        return res;
    }

还有滑动窗口的做法,接下来更新。

leetcode 395. Longest Substring with At Least K Repeating Characters(高质量题)

原文:https://www.cnblogs.com/whyaza/p/10779039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!