3.Longest Substring Without Repeating Characters

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容