Fastest Swift solution accepted so far


  • 0
    R

    Beated 100% submissions
    xD

    The trick is to use s.utf8 here:

    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            var chars = Array(s.utf8)
            var max_len = 0
            
            var char_index = [UInt8:Int]()
            
            var i = 0
            for j in 0..<chars.count {
                if let old_index = char_index.updateValue(j, forKey: chars[j]) {
                    i = max(old_index + 1, i)
                }
                max_len = max(max_len, j - i + 1)
            }
            return max_len
        }
    }
    

  • 0

    try this two pointers version, it's faster :)

    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
        }
    

Log in to reply
 

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