题目:Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = “aab”
Output: “aba”
Example 2:
Input: S = “aaab”
Output: “”
Note:
S will consist of lowercase letters and have length in range [1, 500].
题解:
方法一:用堆,统计字符串中每个字母的出现频率,然后每次取出现最多的两个字母,然后最多出现的在前,少出现的在后面,组成一对,当最后的一对差异大于1时,表示不可能构成一种这样的字符串
python code:
def reorganizeString(self, S):
“”"
:type S: str
:rtype: str
“”"
if len(S)==1:return S
res,dic,n=’’,collections.Counter(S),len(S)
while len(res)<n:
c=dic.most_common(2)
if len©==1 or (not c[-1][-1] and c[0][1]>1):
return ‘’
elif c[0][1]==1 and not c[1][1]:
res+=c[0][0]
else:
res+=(c[0][0]+c[1][0])*c[1][1]
dic[c[0][0]],dic[c[1][0]]=dic[c[0][0]]-c[1][1],dic[c[1][0]]-c[1][1]
return res
c++ code:
class Solution {
public:
string reorganizeString(string S) {
string res = “”;
map<char,int> cntMap;
for(int i = 0; i < S.size(); ++i) {
cntMap[S[i]]++;
}
priority_queue<pair<int,char>> pq;
for(auto p : cntMap) {
if(p.second > (S.size()+1)/2) return "";
pq.emplace(p.second,p.first);
}
pair<int,char> prev(0,' ');
while(!pq.empty()) {
auto curr = pq.top();
//cout << curr.first << " " << curr.second << endl;
pq.pop();
res += curr.second;
--curr.first;
if(prev.first>0) {
pq.emplace(prev);
}
// curr was used to construct res, its removed now so that
// in the next iteration we don't look at it.
prev = curr;
}
return res;
}
};
方法二:多的包含小的,只要把出现频率较小的放在奇位置,出现频率大的放在偶位置即可,当且仅当后面两个一样的时候返回空串
def reorganizeString(self, S: ‘str’) -> ‘str’:
a,h=sorted(sorted(S),key=S.count),len(S)//2
a[1::2],a[::2]=a[:h],a[h:]
return ‘’.join(a)*(a[-1:]!=a[-2:-1])