Algorithm/ct/l2/17-重排字符串.py

34 lines
805 B
Python

import io
import sys
sys.stdin = io.StringIO('''1
aabbccc''') # cabcacb
from collections import Counter
def reorganizeString(str):
cnt = Counter(str)
# 桶的数目等于字符串中最多的元素的数目
bucketNum = cnt.most_common(1)[0][1]
buckets = [[] for _ in range(bucketNum)]
idx = 0
# 优先填充数目最多的元素
for c, num in cnt.most_common():
while num:
buckets[idx].append(c)
# 循环在不同桶中进行填充
idx = (idx + 1) % bucketNum
num -= 1
return "".join(["".join(bucket) for bucket in buckets]) if list(map(len, buckets)).count(1) <= 1 else ""
n = int(input())
str = input()
result = reorganizeString(str)
if result == '':
print('no')
else:
print('yes')
print(result)