Skip to content

Commit 086bcf4

Browse files
add kotlin solution for 438 Find-All-Anagrams-In-A-String.kt
1 parent fbec145 commit 086bcf4

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class FindAllAnagramsinaStringKotlin438 {
2+
fun findAnagrams(s: String, p: String): List<Int> {
3+
if (s.isEmpty() || s.length < p.length) {
4+
return emptyList()
5+
}
6+
val result = mutableListOf<Int>()
7+
val hashArray = IntArray(26)
8+
for (index in p.indices) {
9+
++hashArray[p[index] - 'a']
10+
}
11+
var left = 0
12+
var count = 0
13+
/*
14+
0 1 2 3 4
15+
S: b a b a e ...
16+
P: a b b
17+
for
18+
a b e
19+
P 1 2 0
20+
0 1 1 0 count = 1
21+
1 0 1 0 count = 2
22+
2 0 0 0 count = 3 left = 0 OK
23+
3 0 1 0 count = 2 left = 1 NOT
24+
4 1 1 -1 count = 1 left = 2 NOT
25+
*/
26+
27+
for (index in s.indices) {
28+
if (--hashArray[s[index] - 'a'] >= 0) {
29+
++count
30+
}
31+
if (index >= p.length) {
32+
if (hashArray[s[left++] - 'a']++ >= 0) {
33+
--count
34+
}
35+
}
36+
if (count == p.length) {
37+
result.add(left)
38+
}
39+
}
40+
return result
41+
}
42+
/*
43+
fun findAnagrams(s: String, p: String): List<Int> {
44+
if (s.isEmpty() || s.length < p.length) {
45+
return emptyList()
46+
}
47+
val result = mutableListOf<Int>()
48+
val hashArray = IntArray(26)
49+
for (index in p.indices) {
50+
++hashArray[p[index] - 'a']
51+
--hashArray[s[index] - 'a']
52+
}
53+
if (hashArray.count { it == 0 } == 26) {
54+
result.add(0)
55+
}
56+
for (index in 1..s.length - p.length) {
57+
++hashArray[s[index - 1] - 'a']
58+
--hashArray[s[index + p.length - 1] - 'a']
59+
if (hashArray.count { it == 0 } == 26) {
60+
result.add(index)
61+
}
62+
}
63+
return result
64+
}
65+
*/
66+
}
67+
68+
fun main() {
69+
val solution = FindAllAnagramsinaStringKotlin438()
70+
println(solution.findAnagrams("cbaebabacd", "abc")) // 0,6
71+
println(solution.findAnagrams("abab", "ab")) // 0,1,2
72+
}

0 commit comments

Comments
 (0)