leetcode-master/problems/0767.重构字符串.md

61 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

> **如果对做了一些题目,对字符串还没有整体了解的话,可以看这篇:[字符串经典题目大总结!](https://mp.weixin.qq.com/s/gtycjyDtblmytvBRFlCZJg),相信字符串各种操作就非常清晰了。**
扫了一圈题解,感觉大家的解答都比较高端,我来一个朴实无华的版本。
分为如下三步:
* 用map统计频率字符频率
* 转为vector即数组按频率从大到小排序
* 按奇数位顺序插入,插满之后按偶数位顺序插入
**为什么要先按奇数位插入呢?**
先按奇数位插入,保证最大的字符分散开,因为奇数位总是>=偶数位!
C++代码如下:
```
class Solution {
private:
bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second; // 按照频率从大到小排序
}
public:
string reorganizeString(string S) {
unordered_map<char, int> umap;
int maxFreq = 0;
for (char s : S) {
umap[s]++;
maxFreq = max(umap[s], maxFreq);
}
if (2 * maxFreq - 1 > S.size()) return "";
vector<pair<int, int>> vec(umap.begin(), umap.end());
sort(vec.begin(), vec.end(), cmp); // 给频率排个序
string result(S);
int index = 0;// 先按奇数位散开
for (int i = 0; i < vec.size(); i++) {
while (vec[i].second--) {
result[index] = vec[i].first;
index += 2;
if (index >= S.size()) index = 1; // 奇数位插满了插偶数位
}
}
return result;
}
};
```
* 时间复杂度O(nlogn)
* 空间复杂度O(n)
关于leetcode统计的击败多少多少用户大家不必过于在意想好代码的时间复杂度就够了这个击败多少用户多提交几次可能就击败100%了。
![767. 重构字符串](https://img-blog.csdnimg.cn/202011301035035.png)
> **我是[程序员Carl](https://github.com/youngyangyang04),可以找我[组队刷题](https://img-blog.csdnimg.cn/20201115103410182.png),也可以在[B站上找到我](https://space.bilibili.com/525438321),本文[leetcode刷题攻略](https://github.com/youngyangyang04/leetcode-master)已收录,更多[精彩算法文章](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzUxNjY5NTYxNA==&action=getalbum&album_id=1485825793120387074&scene=173#wechat_redirect)尽在公众号:[代码随想录](https://img-blog.csdnimg.cn/20201124161234338.png),关注后就会发现和「代码随想录」相见恨晚!**
**如果感觉题解对你有帮助,不要吝啬给一个👍吧!**