-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0767-reorganize-string.rb
65 lines (52 loc) · 1.27 KB
/
0767-reorganize-string.rb
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
# frozen_string_literal: true
# 767. Reorganize String
# Medium
# https://leetcode.com/problems/reorganize-string
=begin
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
* 1 <= s.length <= 500
* s consists of lowercase English letters.
=end
# @param {String} s
# @return {String}
def reorganize_string(s)
count_hash = {}
s.each_char do |c|
count_hash[c] = count_hash.fetch(c, 0) + 1
end
sorted_chars = count_hash.sort_by { |k, v| -v }
# If any character occurs more than (N + 1) / 2 times, the task is impossible.
if sorted_chars[0][1] > (s.length + 1) / 2
return ""
end
res = [""] * s.length
idx = 0
sorted_chars.each do |char, count|
count.times do
if idx >= s.length
idx = 1
end
res[idx] = char
idx += 2
end
end
res.join("")
end
# **************** #
# TEST #
# **************** #
require "test/unit"
class Test_length_of_longest_substring < Test::Unit::TestCase
def test_
assert_equal "aba", reorganize_string("aab")
assert_equal "", reorganize_string("aaab")
end
end