LoginSignup
0
0

More than 3 years have passed since last update.

Leetcode #438: Find All Anagrams in a String

Posted at
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
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0