395. The longest substring with at least K repeated characters (string segmentation)

395. The longest substring with at least K repeated characters

Intermediate difficulty 351

Give you a string  s and an integer  k , please find  s the longest substring in, and require that each character in the substring appear more than once  k . Returns the length of this substring.

Example 1:

Input: s = "aaabb", k = 3 Output: 3
 Explanation: The longest substring is "aaa", where'a
 ' is repeated 3 times.

Example 2:

Input: s = "ababbc", k = 2
 Output: 5
 Explanation: The longest substring is "ababb", where'a' is repeated 2 times and'b' is repeated 3 times.

prompt:

  • 1 <= s.length <= 104
  • s Only composed of lowercase English letters
  • 1 <= k <= 105

Problem solution: divide and conquer + string split

  1. Count the number of occurrences of all characters, and find all characters with less than K occurrences
  2. Use these characters with a frequency less than k as cutting points, and cut str into smaller substrings for processing
class Solution {
public:
	int longestSubstring(string s, int k) {
		int ch[26] = { 0 };
		for (auto i : s) {
			ch[i - 'a'] ++;
		}
		string split_ch = "";
		for (int i = 0; i < 26; ++i) {
			if (ch[i] > 0 && ch[i] < k)
			{
				split_ch += (i + 'a');
				break;
			}
		}
		if (split_ch == "")
			return s.length();
		vector<string>split_s = split3(s, split_ch[0]);
		int res = 0;
		for (auto i : split_s) {
			res = max(res, longestSubstring(i, k));
		}
		return res;
	}
	vector<string> split(const string &str, const string &pattern)
	{
		vector<string> res;
		if (str == "")
			return res;
		//在字符串末尾也加入分隔符,方便截取最后一段
		string strs = str + pattern;
		size_t pos = strs.find(pattern);

		while (pos != strs.npos)
		{
			string temp = strs.substr(0, pos);
			res.push_back(temp);
			//去掉已分割的字符串,在剩下的字符串中进行分割
			strs = strs.substr(pos + 1, strs.size());
			pos = strs.find(pattern);
		}

		return res;
	}
    vector<string> split3(const string &str, const char pattern)
    {
        vector<string> res;
        stringstream input(str);   //读取str到字符串流中
        string temp;
        //使用getline函数从字符串流中读取,遇到分隔符时停止,和从cin中读取类似
        //注意,getline默认是可以读取空格的
        while(getline(input, temp, pattern))
        {
            res.push_back(temp);
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/Yanpr919/article/details/114173635