leetcode 767重新分配字符串

题目: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])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值