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]
.
-----------------------------
这题目看起来简单但是有些恶心,没有办法特别简单的code,简单来说有三种思路:
思路一:先摊平了,再利用Python字符串操作交叉
from collections import Counter
class Solution:
def reorganizeString(self, S: str) -> str:
l = len(S)
ca = Counter(S)
tmp, res = [], [None for i in range(l)]
sorted_list = sorted([(v, k) for k, v in ca.items()])
if (sorted_list[-1][0] > (l+1)>>1):
return ""
for cnt, ch in sorted_list:
tmp.extend([ch for i in range(cnt)])
half = l >> 1
res[::2], res[1::2] = tmp[half:], tmp[:half] # python大法好
return "".join(res)
思路二:每次摆出现频率最高的两个,当然就用到了堆
class Solution(object):
def reorganizeString(self, S):
pq = [(-S.count(x), x) for x in set(S)]
heapq.heapify(pq)
if any(-nc > (len(S) + 1) / 2 for nc, x in pq):
return ""
ans = []
while len(pq) >= 2:
nct1, ch1 = heapq.heappop(pq)
nct2, ch2 = heapq.heappop(pq)
#This code turns out to be superfluous, but explains what is happening
#if not ans or ch1 != ans[-1]:
# ans.extend([ch1, ch2])
#else:
# ans.extend([ch2, ch1])
ans.extend([ch1, ch2])
if nct1 + 1: heapq.heappush(pq, (nct1 + 1, ch1))
if nct2 + 1: heapq.heappush(pq, (nct2 + 1, ch2))
return "".join(ans) + (pq[0][1] if pq else '')
思路三:每个都当成桶,但是code也不简洁
class Solution:
def reorganizeString(self, S: str) -> str:
if len(S) < 2:
return S
chars = Counter(S)
highest = max(chars.values())
freq_char_dict = defaultdict(list)
for k, v in chars.items():
freq_char_dict[v].append(k)
out = [None for _ in range(len(S))]
i = 0
while highest > 0:
ch = freq_char_dict.get(highest, [])
if not ch:
highest -= 1
continue
for c in ch:
for _ in range(highest):
out[i] = c
i += 2
if i >= len(S):
i = 1
highest -= 1
out = "".join(out)
for i in range(1, len(out)):
if out[i] == out[i-1]:
return ""
return out