395. Longest Substring with At Least K Repeating Characters

题目

给定一个字符串,给定一个数字k,找这个字符串里的最大子串的长度,子串满足的条件是:里面的每一个字母都出现了至少k次。

例如:

Input:
s = "ababbc", k = 2

Output:
5

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

思路:递归

  • 用一个哈希表看一下这个字符串哪些字符不符合,如果所有字母都符合,就返回长度
  • 把不符合的字符都标出来位置
  • 对每一片连续的充满了符合的字母的子串进行递归,把每一片的结果都存下来,返回最长的那个

程序:
public class Solution {

	    public int longestSubstring(String s, int k) {
	    	char[] str = s.toCharArray();
	    	return findlongest(0, str.length, str, k);
	        
	    }
	    
	    public int findlongest(int start, int end, char[] str, int k) {

	    	if(end - start < k) return 0;
	    	
	    	int[] index = new int[str.length];
	    	//store the times each character appears
	    	HashMap<Character, Integer> count = new HashMap<Character, Integer>();
	    	for(int i = start; i < end; i++) {
	    		Integer tmp = count.get(str[i]);
	    		count.put(str[i], (tmp == null) ? 1 : tmp+1); 
	    	}
	    	
	    	//judge whether the string obey the rule
	    	boolean flag = true;
	    	for(int i = start; i < end; i++) {
	    		//store the position where the illegal characters locate
	    		if(count.get(str[i]) < k) {index[i] = -1; flag = false;}
	    	}
	    	//if obey the rule, return the length
	    	if(flag) return (end - start);
	    	
	    	//if not, find each contiuous 0 in the index, recursive find each substring len,
	    	//and store each lenth in the array len[]
	    	int[] len = new int[end - start + 1];
	    	int sta = start;
	    	int cnt = 0;
	    	int pos = 0;
	    	for(int i = start; i < end; i++) {
	    		if(index[i] == -1 ) {
	    			len[pos++] = findlongest(sta, sta+cnt, str, k);
	    			cnt = 0;
	    			sta = i+1;
	    		} else
	    		cnt++;
	    	}
	    	len[pos++] = findlongest(sta, end, str, k);
	    	  	
	    	
	    	//return the max number in len[]
	    	int max = 0;
	    	for(int i = 0; i < pos; i++) {
	    		if(len[i] > max) max = len[i];
	    	}
	    	return max;
	    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值