# 767. Reorganize String 重构字符串

## # 题目描述：

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:

1. S will consist of lowercase letters and have length in range [1, 500].

## # 解题方法

``````class Solution(object):
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
counter = collections.Counter(S)
ans = "#"
while counter:
stop = True
for item, times in counter.most_common():
if ans[-1] != item:
ans += item
counter[item] -= 1
if not counter[item]:
del counter[item]
stop = False
break
if stop: break
return ans[1:] if len(ans) == len(S) + 1 else ""
``````

``````class Solution(object):
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
_len = len(S)
count = collections.Counter(S)
que = [(-v, c) for c, v in count.items()]
heapq.heapify(que)
res = ""
while _len:
cnt = min(_len, 2)
temp = list()
for i in range(cnt):
if not que:
return ""
v, c = heapq.heappop(que)
res += c
if v + 1 != 0:
temp.append((v + 1, c))
_len -= 1
for x in temp:
heapq.heappush(que, x)
return res
``````

## # 日期

2018 年 6 月 13 日 ———— 腾讯赛圆满结束！两个月修得正果哈哈～～ 2018 年 10 月 14 日 —— 周赛做出来3个题，开心