Skip to content

Commit 1960704

Browse files
committed
Update Swift/438. Find All Anagrams in a String.swift
1 parent 77dff4a commit 1960704

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// 438. Find All Anagrams in a String
2+
// 4120 ms
3+
4+
func findAnagrams(_ s: String, _ p: String) -> [Int] {
5+
let n = p.count
6+
var arr = Array(repeating: 0, count: s.count) , i = 0, c: Character, j = 0
7+
8+
var pArr = Array(repeating: 0, count: 26)
9+
p.utf8.forEach({ pArr[Int($0-97)] += 1 })
10+
let pSet = pArr.enumerated().filter({$0.element > 0}).map({ Character(UnicodeScalar($0.offset + 97)!) })
11+
12+
while i + n <= s.count {
13+
let start = s.index(s.startIndex, offsetBy: i)
14+
let end = s.index(s.startIndex, offsetBy: i + n)
15+
c = s[start]
16+
let t = s[start..<end]
17+
18+
var tArr = Array(repeating: 0, count: 26)
19+
t.utf8.forEach({ tArr[Int($0-97)] += 1 })
20+
21+
if tArr == pArr {
22+
arr[j] = i; j += 1
23+
while i + n < s.count {
24+
let c1 = s[s.index(s.startIndex, offsetBy: i + n)]
25+
if c == c1 {
26+
i += 1
27+
c = s[s.index(s.startIndex, offsetBy: i)]
28+
arr[j] = i; j += 1
29+
} else if !pSet.contains(c1) {
30+
i += n; break
31+
} else {
32+
break
33+
}
34+
}
35+
}
36+
i += 1
37+
}
38+
39+
return Array(arr[0..<j])
40+
}

0 commit comments

Comments
 (0)