Swift 2.x solution in 208ms t=O(n)


  • 0
    A
    class Solution {
        func lengthOfLongestSubstring(s: String) -> Int {
            let characters = Array(s.characters)
            if characters.count < 2 {
                return characters.count
            }else{
                var map = Dictionary<Character, Int>()
                var max = 0,maxtmp = 1
                map[characters[0]] = 0
                for i in 1..<s.characters.count {
                    if let lastPosition = map[characters[i]]{
                        if lastPosition < i - maxtmp {
                            maxtmp++
                        } else {
                            maxtmp = i - lastPosition
                        }
                    }else{
                        maxtmp++
                    }
                    map[characters[i]] = i
                    if maxtmp > max {
                        max = maxtmp
                    }
                }
                return max
            }
        }
    }
    

    Any ways to get this work faster?


Log in to reply
 

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