https://leetcode.com/problems/reorganize-string/description/
套路题了
如果是判断是否可行,判断条件就是最多的不能超过总长度的一半(考虑计数情况)
如果是找方案 就需要优先队列了。。
struct cmp {
bool operator()(const pair<int, int> & a, const pair<int, int>&b) {
if (a.second != b.second ) return a.second < b.second;
return a.first < b.first;
}
};
class Solution {
public:
string reorganizeString(string s) {
vector< pair<char, int> > mem( 256, make_pair('\0', 0) ) ;
for (int i = 0; i < mem.size(); i++)
mem[i].first = (char)i;
for (auto c:s) mem[c].second ++;
priority_queue< pair<int, int>, vector< pair<int, int> >, cmp > q;
for (int i = 0; i < 256; i++) {
if (mem[i].second > (s.size() + 1)/2 ) return "";
if (mem[i].second) {
q.push( mem[i] );
}
}
string ret;
for (int i = 0; i < s.size(); i++) {
pair<int, int> one = q.top(); q.pop();
if ( ret.empty() || ret.back() != one.first ) {
ret += one.first;
one.second--;
q.push(one);
} else {
if (q.empty()) return "";
pair<int, int> two = q.top(); q.pop();
if (ret.back() != two.first) {
ret += two.first;
two.second --;
} else {
return "";
}
if (two.second)
q.push(two);
if (one.second)
q.push(one);
}
}
return ret.size() == s.size() ? ret : "";
}
};