leetcode 767. 重构字符串
程序员文章站
2024-03-16 16:44:52
...
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
struct Node
{
Node() {}
Node(char c_, int cnt)
{
c = c_;
count = cnt;
}
char c;
int count;
friend bool operator < (const Node& other, const Node& other2);
};
bool operator < (const Node& other, const Node& other2)
{
return other.count < other2.count;
}
class Solution {
public:
string reorganizeString(string S) {
priority_queue<Node> que;
map<char, int> mp;
for (char c : S)
{
mp[c]++;
}
for (auto v : mp)
{
que.push(Node(v.first, v.second));
}
string res;
while (que.size() >= 2)
{
Node n1 = que.top();
que.pop();
Node n2 = que.top();
que.pop();
while (n2.count)
{
res += n1.c;
res += n2.c;
n1.count--;
n2.count--;
}
if(n1.count)
que.push(n1);
}
if (que.size() == 1)
{
Node t = que.top();
if (t.count > 1) return "";
else res += t.c;
}
return res;
}
};
上一篇: cocos creator之绘图系统
下一篇: Cocos Creator错误总结
推荐阅读
-
leetcode 767. 重构字符串
-
leetcode——767.重构字符串
-
每天一道LeetCode-----给定字符串s和字符数组words,在s中找到words出现的位置,words内部字符串顺序无要求
-
LeetCode 151. 翻转字符串里的单词
-
LeetCode[字符串] - #3 Longest Substring Without Repeating Characters 博客分类: LeetCode LeetCodeJavaAlgorithm题解String
-
Leetcode 443: 压缩字符串
-
LeetCode 443. 压缩字符串
-
0519leetcode每日一题(c++)——680. 验证回文字符串 Ⅱ
-
LeetCode:521. Longest Uncommon Subsequence I(找出特殊的子字符串)
-
leetcode-344-反转字符串(java|python)