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]
.
思路:
最开始想分奇数位,偶数位填充,按照出现次数从高到低填充,优先选用剩余空间的填,有点贪心的味道
from collections import Counter
class Solution:
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
if len(S) == 1: return S
p = ['']*len(S)
d = Counter(S)
i, j = 0, 1
most = d.most_common(1)[0]
try:
while len(d):
most = d.most_common(1)[0]
if i<j:
for _ in range(most[1]):
p[i] = most[0]
i += 2
else:
for _ in range(most[1]):
p[j] = most[0]
j += 2
d.pop(most[0])
return ''.join(p)
except:
return ''
但是WA,比如每个字母的count为4,4,2,最后会出现2填不进去的情况
错误的原因在于太贪了,每次都把所有的相同字母填进去,note that填进去一个自后,剩余的字母count就要重新计算了
所以就维持一个priority queue实时选取就好了,每次可以实时选取2个字母,也可以选取1个字母(这里以2个为例)
选取1个字母就要注意前后2次选取的字母不要重复
from collections import Counter
import heapq
class Solution:
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
ret = ''
pq = []
c = Counter(S)
for k, v in c.items():
heapq.heappush(pq, (-v, k))
prev_key = ''
while pq:
v, k = heapq.heappop(pq)
if k == prev_key:
if not pq: return ''
vv, kk = heapq.heappop(pq)
heapq.heappush(pq, (v,k))
v, k = vv, kk
ret += k
if v+1<0:
heapq.heappush(pq, (v+1, k))
prev_key = k
return ret
或者写得更简单点
from collections import Counter
import heapq
class Solution:
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
ret = ''
pq = []
c = Counter(S)
for k, v in c.items():
heapq.heappush(pq, (-v, k))
# previous key value
prev_v, prev_k = 0, ''
while pq:
v, k = heapq.heappop(pq)
ret += k
if prev_v<0:
heapq.heappush(pq, (prev_v, prev_k)) # delay one loop to prevent aab
prev_v, prev_k = v+1, k # store current key value for latter enqueue
return ret if len(ret)==len(S) else ''