add: 最长无重复字符的子串
This commit is contained in:
parent
4cb154f7c7
commit
801073e385
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@ -1,8 +1,10 @@
|
||||
{
|
||||
"cSpell.words": [
|
||||
"dvdf",
|
||||
"lcci",
|
||||
"lcof",
|
||||
"nums",
|
||||
"pwwkew",
|
||||
"zhong"
|
||||
]
|
||||
}
|
@ -51,6 +51,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
|
||||
- LintCode 55. 比较字符串 https://www.lintcode.com/problem/compare-strings/description
|
||||
|
||||
- [最长无重复字符的子串](src/string/longest-substring-without-repeating-characters.js)
|
||||
|
||||
- LeetCode 3. 无重复字符的最长子串 https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
|
||||
- LintCode 384. 最长无重复字符的子串 https://www.lintcode.com/problem/longest-substring-without-repeating-characters/description
|
||||
|
||||
## 数组
|
||||
|
||||
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)
|
||||
|
15
src/string/longest-substring-without-repeating-characters.js
Normal file
15
src/string/longest-substring-without-repeating-characters.js
Normal file
@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @param {string} s
|
||||
* @return {number}
|
||||
*/
|
||||
export const lengthOfLongestSubstring = function (s) {
|
||||
let max = 0
|
||||
|
||||
for (let n = 0, len = s.length, inx = 0, set = new Set(); n < len; n++) {
|
||||
if (n !== 0) set.delete(s[n - 1])
|
||||
while (inx < len && !set.has(s[inx])) set.add(s[inx++])
|
||||
max = Math.max(max, inx - n)
|
||||
}
|
||||
|
||||
return max
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { lengthOfLongestSubstring } from '../../src/string/longest-substring-without-repeating-characters'
|
||||
|
||||
test('最长无重复字符的子串', () => {
|
||||
expect(lengthOfLongestSubstring('abcabcbb')).toBe(3)
|
||||
expect(lengthOfLongestSubstring('bbbbb')).toBe(1)
|
||||
expect(lengthOfLongestSubstring('pwwkew')).toBe(3)
|
||||
expect(lengthOfLongestSubstring('')).toBe(0)
|
||||
expect(lengthOfLongestSubstring(' ')).toBe(1)
|
||||
expect(lengthOfLongestSubstring('au')).toBe(2)
|
||||
expect(lengthOfLongestSubstring('dvdf')).toBe(3)
|
||||
})
|
Loading…
Reference in New Issue
Block a user