Swift solution - Two Pointers, HashMap


  • 0
    class Solution {
        func lengthOfLongestSubstring_TwoPointers(_ s: String) -> Int {
            if s.characters.count == 0 {
                return 0
            }
            
            let chars = Array(s.utf8)
            var left = 0
            var right = 1
            var result = right - left
            var i = 0
            
            while right < chars.count {
                i = left
                while i < right {
                    if chars[i] == chars[right] {
                        left = i + 1
                        break
                    }
                    i += 1
                }
                result = max(result, right - left + 1)
                right += 1
            }
            
            return result
        }
        
        func lengthOfLongestSubstring_HashMap(_ s: String) -> Int {
            if s.characters.count == 0 {
                return 0
            }
            
            let chars = Array(s.utf8)
            var cache = [Int](repeatElement(-1, count: 256))
            var maxNum = 0
            var i = 0
            var j = 0
            
            while i < chars.count {
                let index = Int(chars[i])
                if cache[index] != -1 {
                    j = max(j, cache[index] + 1)
                }
                cache[index] = i
                maxNum = max(maxNum, i - j + 1)
                i += 1
            }
            
            return maxNum
        }
    }
    

Log in to reply
 

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