leetcode 395. Longest Substring with At Least K Repeating Characters 最长K个数量的字符 + DFS深度优先搜索

来源:互联网 发布:最优化方法袁亚湘孙文 编辑:程序博客网 时间:2024/06/07 11:11

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次,求这个子串的最大长度,这个是网上看的做法,基本思路如下:首先先遍历统计字符的数量,然后寻找第一个出现不超过k次的字符,从这个字符分成左右两个子串,递归判断,直至找到最大值

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>using namespace std;class Solution {public:    int longestSubstring(string s, int k)    {        if (k <= 0)            return s.length();        else if (s.length() <= 0 || k > s.length())            return 0;        else         {            map<char, int> mmp;            for (char a : s)            {                if (mmp.find(a) == mmp.end())                    mmp[a] = 1;                else                    mmp[a] += 1;            }            int index = 0;            for (index =0; index<s.length(); index++)            {                if (mmp[s[index]] < k)                    break;            }            if (index == s.length())                return s.length();            else            {                string left = s.substr(0, index);                string right = s.substr(index + 1);                int a = longestSubstring(left, k);                int b = longestSubstring(right, k);                return max(a, b);            }        }    }};
阅读全文
0 0