Skip to content

Commit 005a0c7

Browse files
author
liningkang
committed
Update solution/003.Longest Substring Without Repeating Characters/Solution.swift
swift 003
1 parent 5d9bf21 commit 005a0c7

File tree

1 file changed

+31
-0
lines changed
  • solution/003.Longest Substring Without Repeating Characters

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
3+
func lengthOfLongestSubstring(_ s: String) -> Int {
4+
5+
var dict:[String:Int] = [:]
6+
var res = 0
7+
var left = 0
8+
9+
//转数组比 substring 速度快
10+
11+
let strArray = s.map{String($0)}
12+
13+
for i in 0..<strArray.count {
14+
/**
15+
* dict[strArray[i]]! < left 条件
16+
* 当输入字符串为"abbca"的时候,当i=4时,也就是即将要开始遍历最后一个字母a时,此时哈希表表中a对应1
17+
* b对应3,c对应4,left为2,即当前最长的子字符串的左边界为第二个b的位置
18+
* 而第一个a已经不在当前最长的字符串的范围内了,那么对于i=4这个新进来的a
19+
* 应该要加入结果中,而此时未被更新的哈希表中a为1,不是0,如果不判断它和left的关系的话
20+
* 就无法更新结果,那么答案就会少一位,所以需要加dict[strArray[i]]! < left
21+
*/
22+
if dict[strArray[i]] == nil || dict[strArray[i]]! < left {
23+
res = max(res, i - left + 1)
24+
} else {
25+
left = dict[strArray[i]] ?? 0
26+
}
27+
dict[strArray[i]] = i + 1
28+
}
29+
return res
30+
}
31+
}

0 commit comments

Comments
 (0)