1079 ms AC Swift solution


  • 0
    L
    class Solution {
        func findAnagrams(_ s: String, _ p: String) -> [Int] {
            let windowSize = p.characters.count
            guard windowSize > 0 else {
                return [Int]()
            }
    
            var characterCounts = [Int]()
            for _ in 1...26 {
                characterCounts.append(0)
            }
    
            for char in p.characters {
                let distance = getDistance(of: char)
                characterCounts[distance] += 1
            }
    
            var validStarts = [Int]()
            let sChars = Array(s.characters)
            for (index, char) in sChars.enumerated() {
                let distance = getDistance(of: char)
                characterCounts[distance] -= 1
    
                let start = index - windowSize + 1
                guard start >= 0 else {
                    continue
                }
    
                if characterCounts.filter({ $0 > 0 }).isEmpty {
                    validStarts.append(start)
                }
    
                let headCharacter = sChars[start]
                let headCharacterDistance = getDistance(of: headCharacter)
                characterCounts[headCharacterDistance] += 1
            }
    
            return validStarts
        }
    
        private func getDistance(of char: Character, from origin: Character = "a") -> Int {
            let charAscii = Int(String(char).unicodeScalars.first!.value)
            let originAscii = Int(String(origin).unicodeScalars.first!.value)
            return charAscii - originAscii
        }
    }
    

  • 0

    @lx223
    Can you provide same realization in other languages that pass the judger?


  • 0

    @lx223 This could be due to string indexing in Swift is not an O(1) operation, due to the underlying design of unicode encoding where each character is stored in a variable number of bytes. You will have to first convert the string to an array of characters to get around this.

    You can take a look at this Swift solution to another problem to get an idea how to do this:
    https://github.com/soapyigu/LeetCode_Swift/blob/master/String/CountAndSay.swift


  • 0
    L

    @1337c0d3r Yeah, you are right. It is string indexing. I switched to characters array and passed OJ. It took 1079 ms. It is still much slower than Java solution. Thanks for the link.


  • 0
    L

    @xidui Hi, thanks for reply. It is the string indexing thing that doesn't behave the same in Swift as in Java, as mentioned above.


  • 0

    @lx223
    Haha, I am a new comer to swift and also learnt it from @1337c0d3r. Happy that your concern has been dispelled.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.