ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

力扣2182.构造限制重复的字符串

2026/9/15 6:43:50 拓冰建站 浏览量
力扣2182.构造限制重复的字符串

 思路:先记录每个字符的出现次数,构建一个新字符串,从尾取字符,每取一个该字符个数-1,若该字符已经取到有repeatLimit个,则递归取次大的字符,并对应字符个数-1,若没有次大字符了,则直接返回

代码:

class Solution {
public:bool lastchar(string &s, vector<int>& alphabet, int i){    //递归找次大字符if(--i == -1) return false;    //没有返回falseif(alphabet[i] != 0){    alphabet[i]--;    //找到了对应字符个数-1s += i + 'a';    //取出字符return true;    //有返回true}return lastchar(s, alphabet, i);}string repeatLimitedString(string s, int repeatLimit) {vector<int> alphabet(26);    //记录每个字母个数for(auto letter : s)    //记录alphabet[letter - 'a']++;string newstr = "";    //存储结果for(int i = 25; i >= 0; --i){if(alphabet[i] != 0){int count = 0;    //记录当前字符取了几个了while(alphabet[i]){    //取完当前字符为止if(count == repeatLimit){    //若已经取到repeatLimit个if(!lastchar(newstr,alphabet,i)){    //找次大字符,若没有直接返回结果return newstr;}count = 0;    //重置取了几个}alphabet[i]--;    //没有取到repeatLimit个则对应字符个数-1++count;    //取值个数+1newstr += i + 'a';    //取出字符}}}return newstr;}
};