forked from mohitjain/leetcode_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path767_reorganize_string.rb
More file actions
70 lines (58 loc) · 1.6 KB
/
767_reorganize_string.rb
File metadata and controls
70 lines (58 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Leetcode problem: https://leetcode.com/problems/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:
#
# S will consist of lowercase letters and have length in range [1, 500].
#-----------------------------------------------------------------------------------------------------------------------
# @param {String} s
# @return {String}
require_relative 'core/heap'
Character = Struct.new(:character, :counter)
def reorganize_string(s)
data_count = {}
s.split('').each do |char|
data_count[char] = data_count[char].to_i + 1
end
max_heap = Heap.new :> do |a, b|
a.counter == b.counter ? (a.character < b.character) : (a.counter > b.counter)
end
data_count.keys.each do |key|
character = Character.new(key, data_count[key])
max_heap.add character
end
result = ''
while max_heap.size > 1
top = max_heap.pop
top_next = max_heap.pop
result += top.character
result += top_next.character
if top.counter > 1
top.counter -= 1
max_heap.add top
end
if top_next.counter > 1
top_next.counter -= 1
max_heap.add top_next
end
end
if max_heap.size == 1
top = max_heap.pop
return '' if top.counter > 1
return '' if top.character == result[-1]
result += top.character
end
result
end
p reorganize_string 'aab'
p reorganize_string 'aaab'