Skip to content

Commit 992f074

Browse files
committed
Add problem: #3 Longest Substring Without Repeating Characters
1 parent de276f5 commit 992f074

File tree

5 files changed

+48
-0
lines changed

5 files changed

+48
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../problems/0003-longest-palindromic-substring
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../problems/0003-longest-palindromic-substring/
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
### 3. Longest Substring Without Repeating Characters
2+
3+
https://leetcode.com/problems/longest-substring-without-repeating-characters/
4+
5+
Given a string `s`, find the length of the __longest substring__ without repeating characters.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const lengthOfLongestSubstring = function(s) {
6+
/** @var int 當前 char 位置 (1 base) */
7+
let pos = 0
8+
/** @var int 總體最長不重複字串 */
9+
let longest = 0
10+
/** @var int 當前不重複最長字串 */
11+
let currentLength = 0
12+
/** @var Map 所有文字前一次出現的位置 */
13+
const lastOccurs = new Map()
14+
15+
// 每個字母我們都記錄最後一次出現的位置
16+
// - 如果兩次出現的距離小於當前段落長度: 刷新段落長度
17+
// - 如果兩次出現的距離大於當前段落長度: 當前段落長度 + 1
18+
// 找出最長段落
19+
for (const char of s) {
20+
const last = lastOccurs.get(char) || 0
21+
const distance = (++pos - last)
22+
currentLength = distance > currentLength ? currentLength + 1 : distance
23+
longest = Math.max(longest, currentLength)
24+
lastOccurs.set(char, pos)
25+
}
26+
27+
return longest
28+
};
29+
30+
export default lengthOfLongestSubstring
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import lswrc from './longest-substring-without-repeating-characters'
2+
3+
test.each`
4+
s | expected
5+
${'abcabcbb'} | ${3}
6+
${'bbbbb'} | ${1}
7+
${'pwwkew'} | ${3}
8+
${''} | ${0}
9+
`('Longest substring: ($s)', ({ s, expected }) =>
10+
expect(lswrc(s)).toBe(expected)
11+
)

0 commit comments

Comments
 (0)