您的位置:首页 > 其它

LeetCode-Longest Substring Without Repeating Characters

2017-08-18 18:08 344 查看
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个测试用例,时间复杂度太高

后来经过思考,将关注重心从下一次遍历的字符串转移到下一次计数的开始下标上,问题迎刃而解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode