美文网首页
LeetCode答题记录3. 无重复字符的最长子串

LeetCode答题记录3. 无重复字符的最长子串

作者: 渣新iOS程序员sun某 | 来源:发表于2018-08-09 16:12 被阅读0次

    给定一个字符串,找出不含有重复字符的最长子串的长度。
    示例:
    给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。
    给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。
    给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。

    func lengthOfLongestSubstring(_ s: String) -> Int {
        if s.isEmpty {
            return 0
        }
        var charDict = [Character:Int]()
        var index: Int = 0
        var strIndex: String.Index = s.startIndex
        var startIndex: Int = 0
        var endIndex: Int = 0
        var maxLength: Int = 0
        var currentLength: Int = 0
        while strIndex < s.endIndex {
            if charDict[s[strIndex]] == nil {
                endIndex = index
                charDict[s[strIndex]] = index
                currentLength += 1
            }else {
                endIndex = index
                if startIndex < charDict[s[strIndex]]! + 1 {
                    startIndex = charDict[s[strIndex]]! + 1
                    if maxLength < currentLength {maxLength = currentLength}
                    currentLength = endIndex - startIndex + 1
                }else {
                    currentLength += 1
                }
                charDict[s[strIndex]] = index
            }
            index += 1
            strIndex = s.index(after: strIndex)
        }
        if endIndex - startIndex + 1 > maxLength {
            return endIndex - startIndex + 1
        }else {
            return maxLength
        }
    }
    

    解答:
    1、遍历并记录子字符串长度currentLength。
    2、出现重复字符时记录目前子串长度到maxLength中,然后从不重复的位置继续遍历,刷新子字符串长度currentLength。
    3、每次遇到重复字符则重复步骤2。
    4、遍历结束后再更新一次maxLength,即可。
    这里使用了字典来获得重复字符出现的index位置。

    相关文章

      网友评论

          本文标题:LeetCode答题记录3. 无重复字符的最长子串

          本文链接:https://www.haomeiwen.com/subject/aokcbftx.html