Swift, basic solution using dictionary


  • 0
    A
    func lengthOfLongestSubstring(_ s: String) -> Int {
            let strArray = Array(s.characters)
            var hash = [Character: Int]()
            
            var start = 0
            var end = 0
            var s = 0
            var e = 0
            
            if strArray.count == 1 {return 1}        
            if strArray.isEmpty {return 0}
    
            for (i, n) in strArray.enumerated() {
                if let index = hash[n] {
                    if end - start < e - s {
                        end = e
                        start = s
                    }   
                    if index + 1 > s {
                        s = index + 1
                    }
                }
                e += 1
                if i == strArray.count - 1 {
                    if end - start < e - s {
                         return e - s
                    }
                    return end - start
                }
                hash[n] = i
            }
            return -1
        }
    
    

Log in to reply
 

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