Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 438. Find All Anagrams in a String
- func findAnagrams1(_ s: String, _ p: String) -> [Int] {
- var p = Array(p).map{String($0)}
- var s = Array(s).map{String($0)}
- var pCount = [String:Int]()
- var sCount = [String:Int]()
- if p.count > s.count {return []}
- for i in 0..<p.count {
- pCount[p[i], default: 0] += 1
- sCount[s[i], default: 0] += 1
- }
- var result: [Int]
- if pCount == sCount {
- result = [0]
- } else {
- result = []
- }
- var l = 0
- var r = p.count
- while r < s.count {
- sCount[ s[r], default: 0 ] += 1
- sCount[ s[l], default: 0 ] -= 1
- if sCount[ s[l] ] == 0 {
- sCount[ s[l] ] = nil
- }
- l += 1
- r += 1
- if sCount == pCount {
- result.append(l)
- }
- }
- return result
- }
- findAnagrams1("cbaebabacd", "ba")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement