• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

Example 1:

Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:

Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

Analysis:

Given a string s, find out all chars that are invalid (i.e., count < k). The longest substring must reside in one of the substrings divided by those invalid chars. We find out all those possible substrings and recursively address each of them.

NOTE: repeatedly using s.charAt() is actually very slow. So we convert the string to charArray in the first place

 1 public class Solution {
 2     public int longestSubstring(String s, int k) {
 3         return longestSubstring(s.toCharArray(), 0, s.length()-1, k);
 4     }
 5     
 6     public int longestSubstring(char[] arr, int start, int end, int k) {
 7         if (end < start) return 0;
 8         if (end-start+1 < k) return 0;
 9         int[] count = new int[26];
10         for (int i=start; i<=end; i++) {
11             count[arr[i]-'a']++;
12         }
13         for (int i=0; i<26; i++) {
14             if (count[i] == 0) continue;
15             if (count[i] < k) {
16                 int j = start;
17                 for (; j<=end; j++) {
18                     if (arr[j] == (char)('a'+i)) break;
19                 }
20                 int left = longestSubstring(arr, start, j-1, k);
21                 int right = longestSubstring(arr, j+1, end, k); 
22                 return Math.max(left, right);
23             }
24         }
25         return end-start+1;
26     }
27 }

 

posted @ 2016-12-01 11:33  neverlandly  阅读(426)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3