LeetCode 767
Reorganize String
- Problem Description:
对字符串中的字符顺序进行调整,如果能够使相邻字符不相同,返回调整后的任一满足字符串,否则返回空字符串。
具体的题目信息:
https://leetcode.com/problems/reorganize-string/description/
- Example:
- Solution:
- 解题思路:
(1)遍历字符串,记录每一字符出现的次数,用map容器存储
(2)为了对map中元素按照value值排序,引入vector,自定义比较函数,使得出现次数多的字符排在数组前方
(3)进行是否能通过调整使相邻字符不相同的判断:if (v[0].second>ceil(S.length()/2.0))
(4)对于可以调整的情况:先把出现次数最多的字符插入输出字符串res中,对剩下的字符依次从尾部插入【这部分插入我还不太理解 QAQ】
- 编程实现:
class Solution {
public:
static bool cmp(pair<char, int>& p1, pair<char, int>& p2) {
return p1.second>p2.second;
}
string reorganizeString(string S) {
if (S.length() == 0||S.length() == 1) return S;
map<char, int> t;
for (int i = 0; i < S.length(); i++) {
t[S[i]]++;
}
vector<pair<char, int>> v(t.begin(), t.end());
sort(v.begin(), v.end(), cmp);
string res = "";
char temp;
int nextpos;
if (v[0].second>ceil(S.length()/2.0)) return res;
for (int i = 0; i < v.size(); i++) {
if (res.length() == 0) {
while(v[i].second--) {
res.insert(res.begin(), v[i].first);
}
nextpos = res.size()-1;
} else {
while(v[i].second--) {
res.insert(res.begin()+nextpos, v[i].first);
nextpos = (nextpos-1)%res.size();
}
}
}
return res;
}
};