Swift 3 two pointers method 66ms 100%


  • 0
    Y
    class Solution {
        func minWindow(_ s: String, _ t: String) -> String {
     
            let tt = Array(t.utf16).map { Int($0) }
            let ss = Array(s.utf16).map { Int($0) }
            // create hashmap 
            var hash = [Int](repeating: 0, count: 128)
            for n in tt {
                hash[n] += 1
            }
            
            var count = tt.count, start = 0, l = 0, r = 0, length = Int.max
            
            while r < ss.count {
                if hash[ss[r]] > 0 {
                    count -= 1
                }
                hash[ss[r]] -= 1
                r += 1
                while count == 0 {
                    if r - l < length {
                        length = r - l
                        start = l
                    }
                    if hash[ss[l]] == 0 {
                        count += 1
                    }
                    hash[ss[l]] += 1
                    l += 1
                }
            }
            
            if length > ss.count {
                return ""
            }
            
            let index1 = s.index(s.startIndex, offsetBy: start)
            let index2 = s.index(s.startIndex, offsetBy: start + length)
            return s.substring(with: index1..<index2)
        }
    }
    
    

Log in to reply
 

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