Skip to content

Commit 87769c2

Browse files
Merge pull request #205
add new problem 3.06
2 parents 0a15ad9 + 8f5167c commit 87769c2

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package com.github.contest
22

33

4-
import com.github.contest.design.RLEIterator
54
import com.github.contest.math.numberOfPowerfulInt
65
import com.github.contest.slidingWindow.customStructure.rabinKarpMultiPattern
76
import com.github.contest.slidingWindow.customStructure.slidingWindowClassic
7+
import com.github.contest.slidingWindow.findAnagrams
88
import com.github.contest.strings.fullJustify
99
import com.github.contest.strings.subStrHash
1010
import java.util.TreeMap
@@ -16,10 +16,7 @@ import java.util.TreeMap
1616

1717
fun main() {
1818

19-
val rleIterator = RLEIterator(intArrayOf(5, 2, 1, 22))
20-
rleIterator.next(5).also { println(it) }
21-
rleIterator.next(2).also { println(it) }
22-
rleIterator.next(1).also { println(it) }
19+
findAnagrams("abnkjhgidhr", "abn").also { println(it) }
2320
}
2421

2522
infix fun Int.myRange(to: Int): IntRange {

contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,49 @@ fun decrypt(code: IntArray, k: Int): IntArray = when {
724724
}
725725
}
726726

727+
/**
728+
* 438. Find All Anagrams in a String
729+
*/
730+
731+
fun findAnagrams(s: String, p: String): List<Int> {
732+
if (p.length > s.length) return listOf()
733+
734+
val pattern = p.eachCount()
735+
val store = mutableMapOf<Char, Int>()
736+
var left = 0
737+
val k = p.length
738+
val ind = mutableListOf<Int>()
739+
740+
for (right in s.indices) {
741+
val char = s[right]
742+
store[char] = store.getOrDefault(char, 0) + 1
743+
744+
if (right - left == k - 1) {
745+
if (equalMaps(store, pattern)) ind.add(left)
746+
store[s[left]] = store.getOrDefault(s[left], 0) - 1
747+
if (store[s[left]] == 0) store.remove(s[left])
748+
left++
749+
}
750+
751+
}
752+
753+
return ind
754+
}
755+
756+
private fun <K, V : Comparable<V>> equalMaps(first: Map<K, V>, second: Map<K, V>): Boolean {
757+
758+
for ((char, count) in first) {
759+
if (!second.contains(char) || second[char] != count) return false
760+
}
761+
762+
return true
763+
}
764+
765+
private fun String.eachCount(): MutableMap<Char, Int> {
766+
val count = mutableMapOf<Char, Int>()
767+
for (char in this) count[char] = count.getOrDefault(char, 0) + 1
768+
return count
769+
}
727770

728771

729772

0 commit comments

Comments
 (0)