395. Longest Substring with At Least K Repeating Characters

https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87739/Java-Strict-O(N)-Two-Pointer-Solution

window分别为1-26个unique的字母,找出为这个长度的字母的 其中至少有K repeating ones的最长子序列,取最大值

 

 

 1 class Solution {
 2     public int longestSubstring(String s, int k) {
 3         if(s.length() < k) return 0;
 4         int max = 0;
 5         for(int i = 0; i < 26; i++){
 6             int[] arr = new int[26];
 7             int unique = 0;
 8             int lo = 0, hi = 0;
 9             while(hi < s.length()){
10                 boolean valid = true;
11                 if(arr[s.charAt(hi) - 'a']++ == 0) unique++;
12                 hi++;
13                 while(unique > i){  //搞到unique == i
14                     if(arr[s.charAt(lo++) - 'a']-- == 1) unique--;
15                 }
16                 for(int j = 0; j < 26; j++){   //看看存不存在出现但是不到k次数的字母
17                     if(arr[j] > 0 && arr[j] < k){  //注意arr[j] > 0 因为要出现
18                         valid = false;
19                         break;
20                     }
21                 }
22                 if(unique == i && valid){ 
23                     max = Math.max(max, hi-lo); //hi-lo
24                 }
25                 
26             }   
27         }
28         return max;   
29     }
30 }

 

posted @ 2018-10-31 11:32  jasoncool1  阅读(125)  评论(0编辑  收藏  举报