• Longest Substring with At Least K Repeating Characters


    Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路:先统计每个字母出现的频次,如果小于k,那么这个字母必定不会出现在符合要求的子字符串中,那么以此字母为分界点,把字符串分割,重复以上步骤。分治一般会有左右边界,因此,我们可以通过设置左右边界的指针,从字符串两端同时开始进行,遇到频次小于k的字母则跳过,不断往中间收缩,缩减可能符合要求的子字符串的范围。

    class Solution {
        public int longestSubstring(String s, int k) {
            int length = s.length();
            if(length == 0 || length < k)
            {
                return 0;
            }
            if(k < 2)
            {
                return length;
            }
            
            return getResult(s.toCharArray(), k, 0, length - 1);
        }
        
        public static int getResult(char[] chars, int k, int left, int right)
        {
            if(right - left + 1 < k)
            {
                return 0;
            }
            int[] times = new int[26];
            for(int i = left; i <= right; i++)
            {
                times[chars[i] - 'a']++;
            }
            
            while(right - left + 1 >= k && times[chars[left] - 'a'] < k)
            {
                left++;
            }
            while(right - left + 1 >= k && times[chars[right] - 'a'] < k)
            {
                right--;
            }
            for(int i = left; i <= right; i++)
            {
                if(times[chars[i] - 'a'] < k)
                {
                    return Math.max(getResult(chars, k, left, i - 1), getResult(chars, k, i + 1, right));
                }
            }
            return right - left + 1;
        }
    }
  • 相关阅读:
    2020.9.26
    2020.10.2
    判断方法
    sql与include
    File类的获取方法
    【每日日报】第十五天
    【每日日报】第十三天
    【每日日报】第十四天
    两数相加(输入框)
    判断闰年
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/12759342.html
Copyright © 2020-2023  润新知