Leetcode 395.至少有k個重複字符的最長子串

至少有k個重複字符的最長子串

找到給定字符串(由小寫字符組成)中的最長子串 T , 要求 T 中的每一字符出現次數都很多於 k 。輸出 的長度。 java

示例 1: ide

輸入: spa

s = "aaabb", k = 3 字符串

 

輸出: string

3 it

 

最長子串爲 "aaa" ,其中 'a' 重複了 3 次。 io

示例 2: class

輸入: import

s = "ababbc", k = 2 遍歷

 

輸出:

5

 

最長子串爲 "ababb" ,其中 'a' 重複了 2 次, 'b' 重複了 3 次。

 

要求是找出最長的子串,子串中的每個字符都要重複至少k次。

 

 

思路是分治法。

要找s[i,j]的最大子串,先統計頻數,而後遍歷一遍頻數,找出第一個頻數小於k且大於0的字符,而後找出這個字符的位置,接下來的分析很重要,這個字符必定不能出如今任何的子串中,由於i,j是整個的子串,在ij裏面頻數都沒有達到k,那麼在ij的任何子串中,這個字符也不可能達到頻數k。因此不能有這個字符,那麼就在這個位置作一個分治,返回前半部分和後半部分的最大值。

 

 1 import java.util.Stack;
 2 
 3 public class Solution{
 4     public int longestSubstring(String s, int k) {
 5         return longestSubstringSub(s, k, 0, s.length() - 1);
 6     }
 7 
 8     private int longestSubstringSub(String s, int k, int start, int end){
 9         if(start > end) return 0;
10         int[] count = new int[26];
11         for(int i = start; i <= end; i++){
12             count[s.charAt(i) - 'a']++;
13         }
14         for(int i = 0; i < 26; i++){
15             if(count[i] > 0 && count[i] < k){
16                 int pos = s.indexOf((char)(i + 'a'), start);
17                 return Math.max(longestSubstringSub(s, k, start, pos - 1), longestSubstringSub(s, k, pos + 1, end));
18             }
19         }
20         return end - start + 1;
21     }
22 }
相關文章
相關標籤/搜索