func findAnagrams(_ s: String, _ p: String) -> [Int] {
if p.count > s.count {
return []
}
var pDict = Array(repeating: 0, count: 26)
for char in p {
pDict[Int(char.asciiValue!) - 97] += 1
}
var s = Array(s)
var answer = [Int]()
var sDict = Array(repeating: 0, count: 26)
for i in stride(from: 0, to: p.count, by: 1) {
sDict[Int(s[i].asciiValue!) - 97] += 1
}
if isAnagram(sDict, pDict) {
answer.append(0)
}
for i in stride(from: 0, to: s.count - p.count, by: 1) {
sDict[Int(s[i].asciiValue!) - 97] -= 1
sDict[Int(s[i+p.count].asciiValue!) - 97] += 1
if isAnagram(sDict, pDict) {
answer.append(i+1)
}
}
return answer
}
private func isAnagram(_ s: [Int], _ p: [Int]) -> Bool {
for i in stride(from: 0, to: 26, by: 1) {
if s[i] != p[i] {
return false
}
}
return true
}
More than 3 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
00