add: 最长无重复字符的子串

This commit is contained in:
yi-ge 2020-05-02 16:06:08 +08:00
parent 4cb154f7c7
commit 801073e385
4 changed files with 33 additions and 0 deletions

View File

@ -1,8 +1,10 @@
{ {
"cSpell.words": [ "cSpell.words": [
"dvdf",
"lcci", "lcci",
"lcof", "lcof",
"nums", "nums",
"pwwkew",
"zhong" "zhong"
] ]
} }

View File

@ -51,6 +51,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LintCode 55. 比较字符串 https://www.lintcode.com/problem/compare-strings/description - 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) - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)

View 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
}

View File

@ -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)
})