2016/9/21 leetcode 解题笔记 395.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.

题目大意就是要找到字符串的一个子字符串 这个字符串中每个字符出现的次数都要大于K次 并且要返回最长的那个子字符串的长度
解题思路
1;由于题目中说每一个字符都是小写的 我们可以用一个数组来表示每个字母出现的次数 总共有26个小写字母 数组的长度设为26 int[]=new int[26];
2;让每个字母与数组下标 相对应 a对应0 b对应1 可以这样 index=character-'a' 如果chararcter是a 那么index=0;是b index为1;
3;依次读取 int数组中每个字母出现的次数 对于一次都没出现的字母 直接continue 如果字符串中有字母出现次数小于K 那么子字符串肯定不包含该字母,找到该字母下标后 再从该字母左边的字符串 和右边的字符
串中寻找最大子字符串 如果没有字母出现次数小于K 直接返回该字符串长度;
代码如下
public int longestSubstring(String s, int k) {
	    char[] str = s.toCharArray();
	    return helper(str,0,s.length(),k);
	}
	private int helper(char[] str, int start, int end,  int k){
	    if(end<start) return 0;
	    if(end-start<k) return 0;//substring length shorter than k.
	    int[] count = new int[26];
	    //统计每个字母出现的次数
	    for(int i = start;i<end;i++){
	        int idx = str[i]-'a';
	        count[idx]++;
	    }
	    for(int i = 0;i<26;i++){
	    	//如果字母一次都不出现 直接跳过
	        if(count[i]==0)continue;
	        //找到出现次数小于K的字母
	        if(count[i]<k){
	            for(int j = start;j<end;j++){
	            	//找到它首次出现的位置
	                if(str[j]==i+'a'){
	                    int left = helper(str,start,j,k);
	                    int right = helper(str,j+1,end,k);
	                    return Math.max(left,right);
	                }
	            }
	        }
	    }
	    return end-start;
	}

  

原文地址:https://www.cnblogs.com/Mrjie/p/5892311.html