Skip to content

Commit ec769bb

Browse files
committed
[LEET] Reorganize String (Medium)
1 parent 7a5bb8c commit ec769bb

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

김지호/4주차/260119.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# https://leetcode.com/problems/reorganize-string/description/?envType=problem-list-v2&envId=whcgn2eg
2+
3+
from math import ceil
4+
5+
class Solution:
6+
def reorganizeString(self, s: str) -> str:
7+
answer = [''] * len(s)
8+
counts = {}
9+
for string in s:
10+
if string in counts: counts[string] += 1
11+
else: counts[string] = 1
12+
13+
# 내림차순 정렬
14+
sort = sorted(counts.items(), key=lambda x: x[1], reverse=True)
15+
16+
# 불가능조건
17+
if sort[0][1] > ceil(len(s) / 2):
18+
answer = ''
19+
return answer
20+
21+
i = 0
22+
for key, _ in sort:
23+
while counts[key] > 0:
24+
answer[i] = key
25+
i += 2
26+
counts[key] -= 1
27+
if i >= len(answer):
28+
i = 1
29+
30+
return ''.join(answer)
31+
32+
answer = Solution()
33+
print(answer.reorganizeString("aaab"))

0 commit comments

Comments
 (0)