Skip to content

Commit 9d37073

Browse files
committed
Longest substring without repeating characters.
1 parent 9e18988 commit 9d37073

File tree

4 files changed

+70
-0
lines changed

4 files changed

+70
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
Given a string s, find the length of the longest substring without repeating characters.
3+
4+
 
5+
6+
Example 1:
7+
Input: s = "abcabcbb"
8+
Output: 3
9+
Explanation: The answer is "abc", with the length of 3.
10+
11+
Example 2:
12+
Input: s = "bbbbb"
13+
Output: 1
14+
Explanation: The answer is "b", with the length of 1.
15+
16+
Example 3:
17+
Input: s = "pwwkew"
18+
Output: 3
19+
Explanation: The answer is "wke", with the length of 3.
20+
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
21+
 
22+
23+
Constraints:
24+
- 0 <= s.length <= 5 * 104
25+
- s consists of English letters, digits, symbols and spaces.
26+
*/
27+
class Solution {
28+
func lengthOfLongestSubstring(_ s: String) -> Int {
29+
guard !s.isEmpty else { return 0 }
30+
var max = 0
31+
var current = 0
32+
var subStrArr = [s.first!]
33+
for e in s {
34+
if !subStrArr.contains(e) {
35+
subStrArr.append(e)
36+
current += 1
37+
if current > max {
38+
max = current
39+
}
40+
} else {
41+
let firstIndex: Int = subStrArr.firstIndex(of: e)!
42+
subStrArr = Array(subStrArr[(firstIndex + 1)...])
43+
current = subStrArr.count
44+
45+
subStrArr.append(e)
46+
current += 1
47+
if current > max {
48+
max = current
49+
}
50+
}
51+
}
52+
return current > max ? current : max
53+
}
54+
}
55+
56+
let s = Solution()
57+
let r = s.lengthOfLongestSubstring("abcabcbb")
58+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/3.Longest Substring Without Repeating Characters.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,4 @@
106106
#### Medium
107107

108108
1. [Min Stack](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/155.Min%20Stack.playground/Contents.swift)
109+
1. [Longest Substring Without Repeating Characters](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/3.Longest%20Substring%20Without%20Repeating%20Characters.playground/Contents.swift)

0 commit comments

Comments
 (0)