Skip to content

Commit 9d61dc8

Browse files
author
Yi Gu
committed
[String] add solution to Longest Substring Without Repeating Characters
1 parent af87000 commit 9d61dc8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
3+
* Primary idea: Use a set to hold characters and then iterate the string,
4+
* update maxLen, set, startIdx encountering duplicates
5+
*
6+
* Note: Swift does not have a way to access a character in a string with O(1),
7+
* thus we have to first transfer the string to a character array
8+
* Time Complexity: O(n), Space Complexity: O(n)
9+
*
10+
*/
11+
12+
class LongestSubstringWithoutRepeatingCharacters {
13+
func lengthOfLongestSubstring(s: String) -> Int {
14+
guard s.characters.count != 0 else {
15+
return 0
16+
}
17+
18+
var set = Set<Character>()
19+
var maxLen = 0
20+
var startIndex = 0
21+
var chars = [Character](s.characters)
22+
23+
for i in 0 ..< chars.count {
24+
var current = chars[i]
25+
26+
if set.contains(current) {
27+
maxLen = max(maxLen, i - startIndex)
28+
while chars[startIndex] != current {
29+
set.remove(chars[startIndex])
30+
startIndex += 1
31+
}
32+
startIndex += 1
33+
} else {
34+
set.insert(current)
35+
}
36+
}
37+
38+
maxLen = max(maxLen, chars.count - startIndex)
39+
40+
return maxLen
41+
}
42+
}

0 commit comments

Comments
 (0)