-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.kt
More file actions
44 lines (39 loc) · 1.28 KB
/
MinimumWindowSubstring.kt
File metadata and controls
44 lines (39 loc) · 1.28 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
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/minimum-window-substring/)
*/
class MinimumWindowSubstring {
fun minWindow(s: String, t: String): String {
val charsCount = initCharsCount(t)
var answer = ""
var left = 0
var right = -1
var remainsToFind = t.length
while (left <= s.length - t.length) {
if (remainsToFind > 0 && right < s.length - 1) {
right++
charsCount.computeIfPresent(s[right]) { _, old ->
if (old > 0) remainsToFind--
old - 1
}
} else {
left++
charsCount.computeIfPresent(s[left - 1]) { _, old ->
if (old >= 0) remainsToFind++
old + 1
}
}
if (remainsToFind == 0 && (right - left < answer.length || answer.isEmpty())) {
answer = s.substring(left, right + 1)
}
}
return answer
}
private fun initCharsCount(str: String): MutableMap<Char, Int> {
val charsCount = HashMap<Char, Int>()
for (ch in str) {
charsCount[ch] = charsCount.getOrDefault(ch, 0) + 1
}
return charsCount
}
}