Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions 0767.Reorganize-String/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 767.Reorganize String

## step1

heapを使う解法を思いつく

時間計算量は、文字列をK種類としたときO(Nlog K)。今K=26なのでほぼ線形。

## step2

https://leetcode.com/problems/reorganize-string/solutions/3947780/100-2-approaches-priority-queue-sort-by-66wlu/?envType=problem-list-v2&envId=7p5x763

計算量は O(N)。こちらの方が速い。

面接で聞かれたとしたらこちらまで聞かれるのだろうか。
32 changes: 32 additions & 0 deletions 0767.Reorganize-String/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import heapq
import collections


class Solution:
def reorganizeString(self, s: str) -> str:
if len(s) == 1:
return s

counter = collections.Counter(s)
most_common = counter.most_common()

if most_common[0][1] > (len(s) - 1) // 2 + 1:
return ""

count_and_letter = [(count, c) for (c, count) in most_common]
heapq.heapify_max(count_and_letter)
result = []

while len(result) < len(s):
count, c = heapq.heappop_max(count_and_letter)
result.append(c)
count_next = 0
if len(count_and_letter) > 0:
count_next, c_next = heapq.heappop_max(count_and_letter)
result.append(c_next)
if count > 1:
heapq.heappush_max(count_and_letter, (count - 1, c))
if count_next > 1:
heapq.heappush_max(count_and_letter, (count_next - 1, c_next))

return "".join(result)
30 changes: 30 additions & 0 deletions 0767.Reorganize-String/step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import collections


class Solution:
def reorganizeString(self, s: str) -> str:
counter = collections.Counter(s)
n = len(s)

most_common_char, max_count = counter.most_common(1)[0]

if max_count > (n + 1) // 2:
return ""

result = [""] * n
index = 0

for _ in range(max_count):
result[index] = most_common_char
index += 2

del counter[most_common_char]

for char, count in counter.items():
for _ in range(count):
if index >= n:
index = 1
result[index] = char
index += 2

return "".join(result)
29 changes: 29 additions & 0 deletions 0767.Reorganize-String/step3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import collections


class Solution:
def reorganizeString(self, s: str) -> str:
counter = collections.Counter(s)
most_common_letter, most_common_count = counter.most_common()[0]

if most_common_count > (len(s) + 1) // 2:
return ""

result = [""] * len(s)
index = 0
while most_common_count > 0:
result[index] = most_common_letter
index += 2
most_common_count -= 1

del counter[most_common_letter]

for letter, count in counter.items():
while count > 0:
if index >= len(s):
index = 1
result[index] = letter
index += 2
count -= 1

return "".join(result)