-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0767-reorganize-string.kt
76 lines (63 loc) · 1.82 KB
/
0767-reorganize-string.kt
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
71
72
73
74
75
76
class Solution {
fun reorganizeString(s: String): String {
var count = HashMap<Char, Int>().apply {
for (c in s)
this[c] = getOrDefault(c, 0) + 1
}
val maxHeap = PriorityQueue<Pair<Int, Char>>() { a, b ->
b.first - a.first
}
for ((ch, cnt) in count)
maxHeap.add(cnt to ch)
var prev: Pair<Int, Char>? = null
var res = StringBuilder()
while (maxHeap.isNotEmpty() || prev != null) {
if (maxHeap.isEmpty() && prev != null)
return ""
var (cnt, ch) = maxHeap.poll()
res.append(ch)
cnt--
prev?.let {
maxHeap.add(it)
prev = null
}
if (cnt != 0)
prev = cnt to ch
}
return res.toString()
}
}
// another solution without heap
class Solution {
fun reorganizeString(s: String): String {
val freq = IntArray (26).apply {
for (c in s) this[c - 'a']++
}
var maxFreq = -1
var maxChar = -1
for (letter in 0..25) {
if (freq[letter] > maxFreq) {
maxFreq = freq[letter]
maxChar = letter
}
}
if (maxFreq > (s.length + 1) / 2) return ""
var i = 0
val res = CharArray (s.length).apply {
while (freq[maxChar] > 0) {
this[i] = 'a' + maxChar
i += 2
freq[maxChar]--
}
}
for (letter in 0..25) {
while (freq[letter] > 0) {
if (i > s.lastIndex) i = 1
res[i] = 'a' + letter
i += 2
freq[letter]--
}
}
return res.joinToString("")
}
}