給定一個(gè)字符串,請(qǐng)你找出其中不含有重復(fù)字符的 最長(zhǎng)子串 的長(zhǎng)度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "abc",所以其長(zhǎng)度為 3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "b",所以其長(zhǎng)度為 1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "wke",所以其長(zhǎng)度為 3。
請(qǐng)注意,你的答案必須是 子串 的長(zhǎng)度,"pwke" 是一個(gè)子序列,不是子串。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
一次解答:暴力法
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var tempString = ""
var resultCount = 0
for c in s {
let subString = String.init(c)
if tempString.contains(subString) {
var repeatLength = 0
for _c in tempString {
repeatLength += 1
if _c == subString.first! {
break
}
}
tempString = String(tempString.suffix(tempString.count - repeatLength))
}
tempString += subString
if resultCount <= tempString.count {
resultCount = tempString.count
}
}
return resultCount
}
}
執(zhí)行結(jié)果:通過
執(zhí)行用時(shí) :256 ms
, 在所有 Swift 提交中擊敗了22.67%的用戶
內(nèi)存消耗 :21.6 MB, 在所有 Swift 提交中擊敗了10.23%的用戶
結(jié)果不是很理想
二次解答:滑動(dòng)窗口
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var ans = 0
var startIndex = 0
var endIndex = 0
var dict: [Character : Int] = [:]
for c in s {
if let val = dict[c] {
startIndex = max(val, startIndex)
}
ans = max(endIndex - startIndex + 1, ans)
endIndex += 1
dict[c] = endIndex
}
return ans
}
}
執(zhí)行結(jié)果:通過
執(zhí)行用時(shí) :36 ms, 在所有 Swift 提交中擊敗了84.24%的用戶
內(nèi)存消耗 :20.9 MB, 在所有 Swift 提交中擊敗了48.28%的用戶
滑動(dòng)窗口方法無疑比暴力破解性能要高出很多,但是內(nèi)存待優(yōu)化。。