LeetCode #3 Longest Substring Without Repeating Characters
Question
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.
Solution
Approach #1
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
let arr = Array(s.utf16)
let count = arr.count
var map: [UTF16.CodeUnit : Int] = [:]
var i = 0
var j = 0
var maxLength = 0
while i < count, j < count {
if let index = map[arr[j]] {
i = max(i, index + 1)
}
map[arr[j]] = j
j += 1
maxLength = max(maxLength, j - i)
}
return maxLength
}
}
Time complexity: O(n).
Space complexity: O(m). m is the size of map.
注意,以下代码的思路和上面完全一样,但结果是“Time Limit Exceeded”
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var map: [Character : Int] = [:]
var i = 0
var j = 0
var maxLength = 0
let count = s.characters.count
while i < count, j < count {
let endChar = s[s.index(s.startIndex, offsetBy: j)]
if let index = map[endChar] {
i = max(i, index + 1)
}
map[endChar] = j
j += 1
maxLength = max(maxLength, j - i)
}
return maxLength
}
}
原因是,String 以 String.Index 取下标比较耗时,不如数组的随机访问效率高。参见:http://www.cnblogs.com/silence-cnblogs/p/6877463.html
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6878223.html