Swift solution - Two Pointers


  • 0
    class Solution {
        func checkInclusion(_ s1: String, _ s2: String) -> Bool {
            if s1.characters.count > s2.characters.count {
                return false
            }
            
            let chars1 = Array(s1.characters)
            let chars2 = Array(s2.characters)
            let len1 = chars1.count
            let len2 = chars2.count
            var counts = [Int](repeatElement(0, count: 256))
            
            for i in 0..<len1 {
                counts[String(chars1[i]).asciiValue] += 1
                counts[String(chars2[i]).asciiValue] -= 1
            }
            if allZero(counts) {
                return true
            }
            for i in len1..<len2 {
                counts[String(chars2[i]).asciiValue] -= 1
                counts[String(chars2[i - len1]).asciiValue] += 1
                if allZero(counts) {
                    return true
                }
            }
            
            return false
        }
        
        private func allZero(_ counts: [Int]) -> Bool {
            for i in 0..<256 {
                if counts[i] != 0 {
                    return false
                }
            }
            return true
        }
    }
    

Log in to reply
 

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