LeetCode-Longest Substring Without Repeating Characters

Q:

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

Examples:

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.

S: Time:O(n) Space: O(min(m,n)),m = s.characters.count n is size of currentCharactersMap

func lengthOfLongestSubstring(_ s: String) -> Int {
    if s.characters.count == 0 {
        return 0
    }

    var charArray: [CChar] = s.cString(using: .utf8)!
    charArray.remove(at: charArray.count - 1)
    var maxLength = 0
    var currentCharactersMap = Dictionary<CChar,Int>()
    var currentStartIndex = 0
    for i in 0..<charArray.count {
        let item = charArray[i]
        if currentCharactersMap[item] != nil {
            currentStartIndex = max(currentStartIndex, currentCharactersMap[item]!)
        }

        maxLength = max(maxLength, i-currentStartIndex+1)
        currentCharactersMap.updateValue(i+1, forKey: item)

    }


    return maxLength
}

总结:
一开始的思路是遍历字符串,在map中保存当前被遍历过的字符,每次查找当前字符是否出现过,如果出现过,就把上一次出现的字符后一个字符开始的字符串当作新的字符串进行递归。发现这样通不过第983个测试用例,时间复杂度太高

后来经过思考,将关注重心从下一次遍历的字符串转移到下一次计数的开始下标上,问题迎刃而解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值