diff --git a/.vscode/settings.json b/.vscode/settings.json index 14567ee..38e1d7b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,10 @@ { "cSpell.words": [ + "dvdf", "lcci", "lcof", "nums", + "pwwkew", "zhong" ] } \ No newline at end of file diff --git a/README.md b/README.md index 993358f..a60a346 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/string/longest-substring-without-repeating-characters.js b/src/string/longest-substring-without-repeating-characters.js new file mode 100644 index 0000000..e9a50b2 --- /dev/null +++ b/src/string/longest-substring-without-repeating-characters.js @@ -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 +} diff --git a/test/string/longest-substring-without-repeating-characters.test.js b/test/string/longest-substring-without-repeating-characters.test.js new file mode 100644 index 0000000..10b2ee6 --- /dev/null +++ b/test/string/longest-substring-without-repeating-characters.test.js @@ -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) +})