zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    java插入语句中有单引号的处理
    mybatis批量插入
    用Resttemple从数据接口中取出数据
    java1.8Stream流式算法
    rabbitmq启动命令
    【MySQL】Mysql模糊查询like提速优化
    Mybatis基础知识点:trim标签的使用
    java8 array、list操作 汇【20】)- (FlatMap)用法汇总
    编写一个定制的收集器
    mysql
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/12759342.html
Copyright © 2011-2022 走看看