LeetCode 767. 重构字符串(C++、python)

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

若可行,输出任意可行的结果。若不可行,返回空字符串。

示例 1:

输入: S = "aab"
输出: "aba"

示例 2:

输入: S = "aaab"
输出: ""

注意:

S 只包含小写字母并且长度在[1, 500]区间内。

C++

class Solution {
public:
    string reorganizeString(string S) 
    {
        int n=S.length();
        int a[26]={0};
        for(int i=0;i(n+1)/2)
            {
                return "";
            }
        }
        priority_queue> temp;
        for(int i=0;i<26;i++)
        {
            if(a[i]>0)
            {
                temp.push(pair(a[i],i+'a'));                
            }
        }
        string res="";
        while(temp.size()>1)
        {
            auto s1=temp.top();
            temp.pop();
            auto s2=temp.top();
            temp.pop();
            res+=s1.second;
            res+=s2.second;
            if(s1.first>1)
            {
                s1.first--;
                temp.push(s1);
            }
            if(s2.first>1)
            {
                s2.first--;
                temp.push(s2);
            }
        }
        if(temp.size()>0)
        {
            res+=temp.top().second;
        }
        return res;        
    }
};

python

import queue
class Solution:
    def reorganizeString(self, S):
        """
        :type S: str
        :rtype: str
        """
        res=""
        n=len(S)
        a=[0 for i in range(26)]
        for i in range(n):
            a[ord(S[i])-ord('a')]+=1
        for i in range(26):
            if a[i]>(n+1)//2:
                return res
        que=queue.PriorityQueue()
        for i in range(26):
            if(a[i]>0):
                que.put([-a[i],chr(i+ord('a'))])
        while que.qsize()>1:
            s1=que.get()
            s2=que.get()
            res+=s1[1]
            res+=s2[1]
            if s1[0]<-1:
                s1[0]+=1
                que.put(s1)
            if s2[0]<-1:
                s2[0]+=1
                que.put(s2)
        if que.qsize()>0:
            res+=que.get()[1]
        return res

 

你可能感兴趣的:(LeetCode,优先队列)