[WXM] LeetCode 395. Longest Substring with At Least K Repeating Characters C++

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.

Approach

  1. 题目大意找到最长的里面的字母都至少出现了K次的连续字符串。这道题我采用了深搜的办法解决,我设定一个区间,一开始的区间为整个字符串,我们映射所有的字母的次数,然后我们将这个区间内的所有字母次数没有到达K次的作为新的区间边界,然后再对这些新的区间边界进行深搜,知道有一个区间内所有字母的次数都到达了K次,然后取其长度的最大值。

Code

class Solution {
public:
	int res = 0;
	void DFS(const string &s,int left,int right,int k) {
		if (right - left+1 < k)return;
		vectorletter(26, 0);
		for (int i = left; i <= right; i++) {
			letter[s[i] - 'a']++;
		}
		int j = left;
		bool flag = false;
		for (int i = left; i <= right; i++) {
			if (letter[s[i] - 'a']

你可能感兴趣的:(String)