Swift 3 Two pointers with Hash method beats 98%


  • 1
    Y
    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            // construct the hashmap
            var hash = [Int](repeating: 0, count: 256)
            let str = Array(s.utf16).map { Int($0) }
            
            let len = str.count
            var ans = 0
            var j = 0
            for i in 0..<len {
                while j < len && hash[str[j]] == 0 {
                    hash[str[j]] = 1
                    j += 1
                }
                ans = max(ans, j - i)
                hash[str[i]] = 0
            }
            return ans
        }
    }
    
    
    

Log in to reply
 

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