-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCutoutsToGenerateString.kt
49 lines (45 loc) · 1.61 KB
/
CutoutsToGenerateString.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
package algorithmdesignmanualbook.datastructures
import _utils.UseCommentAsDocumentation
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* You are given a search string and a magazine.
* You seek to generate all the characters in search string by cutting them out from the magazine.
* Give an algorithm to efficiently determine whether the magazine contains all the letters in the search string
*
* Notes:
* * Cases matters
* * Whitespace doesn't matter
*/
@UseCommentAsDocumentation
fun isGenerateStringFromCutoutPossible(searchStr: String, magazine: String): Boolean {
val frequency = mutableMapOf<Char, Int>()
searchStr.replace(" ", "").forEach {
frequency[it] = frequency.getOrDefault(it, 0) + 1
}
magazine.forEach {
if (frequency.containsKey(it)) {
val newCounts = frequency[it]!!.minus(1)
if (newCounts == 0) {
frequency.remove(it)
} else {
frequency[it] = newCounts
}
}
}
if (frequency.isNotEmpty()) {
println("Requires: $frequency")
}
return frequency.isEmpty()
}
fun main() {
assertFalse { isGenerateStringFromCutoutPossible("hello", "Give an algorithm") }
assertTrue { isGenerateStringFromCutoutPossible("sing me a zing", "You are given a search string and a magazine") }
assertFalse { isGenerateStringFromCutoutPossible("you", "You are given a search string and a magazine") }
assertTrue {
isGenerateStringFromCutoutPossible(
"You give me a gain",
"You are given a search string and a magazine"
)
}
}