美文网首页
3.Longest Substring Without Repe

3.Longest Substring Without Repe

作者: 小伙鸡 | 来源:发表于2017-04-20 16:19 被阅读0次

    Given a string, find the length of the longest substring without repeating characters.

    Given "abcabcbb", the answer is "abc", which the length is 3.
    Given "bbbbb", the answer is "b", with the length of 1.
    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    答案:(发现用C刷题好辛苦,还是边学Swift边刷吧)

    分析:创建一个 char-int 的hashMap,没有重复temMax++,重复的话,判断重复之间有没有其他的重复例如 ABCBA,A之间有B重复,这时候temMax++就可以了
    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            let charArr = Array(s.characters);
            let strLen = charArr.count
            if strLen <= 1  {
                return strLen
            }
            var maxLen = 1
            var hashMap = Dictionary<Character,Int>()
            var temMax = 1
            hashMap[charArr[0]] = 0
        
            for i in 1...strLen-1 {
                if let lastPosition = hashMap[charArr[i]] {
                    if temMax + lastPosition < i {
                        temMax += 1
                    }
                    else {
                        temMax = i - lastPosition
                    }
                }
                else {
                    temMax += 1
                }
                hashMap[charArr[i]] = i
                if temMax > maxLen {
                    maxLen = temMax
                }
            }
            return maxLen
        }
    }
    

    性能:
    时间复杂度:O(n)
    runtime:179 ms
    beats 87.62% submissions

    相关文章

      网友评论

          本文标题:3.Longest Substring Without Repe

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