剑指 Offer II 016. 不含重复字符的最长子字符串

滑动窗口。。
遍历字符串 如果字典中不包含字符的话 右指针往右移动 统计最大长度
当遇到字典中包含的时候 开始移动左指针 移除左指针对应位置的元素。。因为移动的时候还有重复的 说明没有移动到正确的位置。。 那么中间这段字符就需要清空掉。。
直到字典中不会包含重复的元素为止 再重新统计字符长度



func lengthOfLongestSubstring(_ s: String) -> Int {
       if s.count == 0 {
            return 0
        }
       let array = Array(s)
       var count = 0
       var dict = Dictionary()
       var left = 0
       var right = 0
        while right < array.count {
             
            if dict[array[right]] == nil {
                
                dict[array[right]] = 1
                count = max(count,dict.count)
                right += 1

            } else {
                
                while dict[array[right]] != nil {
                    
                    dict[array[left]] = nil
                    left += 1
                    
                }
             
            }

        }
      
        return count

    }

你可能感兴趣的:(剑指 Offer II 016. 不含重复字符的最长子字符串)