From c371738884d73d9cf67f97f0375499b1b548e709 Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 24 May 2020 12:38:29 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=AE=9A=E9=95=BF=E5=AD=90=E4=B8=B2?= =?UTF-8?q?=E4=B8=AD=E5=85=83=E9=9F=B3=E7=9A=84=E6=9C=80=E5=A4=A7=E6=95=B0?= =?UTF-8?q?=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 1 + README.md | 4 ++ ...f-vowels-in-a-substring-of-given-length.js | 45 +++++++++++++++++++ ...els-in-a-substring-of-given-length.test.js | 6 +++ 4 files changed, 56 insertions(+) create mode 100644 src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js create mode 100644 test/string/maximum-number-of-vowels-in-a-substring-of-given-length.test.js diff --git a/.vscode/settings.json b/.vscode/settings.json index 4c3c287..0f9d0d1 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,6 +6,7 @@ "Paddr", "Prinme", "abcdefg", + "abciiidef", "cdefgab", "chuan", "defang", diff --git a/README.md b/README.md index 49e60b4..50e2dac 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 5416. 检查单词是否为句中其他单词的前缀 +- [定长子串中元音的最大数目](src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js) + + - LeetCode 5417. 定长子串中元音的最大数目 + ## 数组/队列/集合/映射 - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js) diff --git a/src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js b/src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js new file mode 100644 index 0000000..996c35c --- /dev/null +++ b/src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js @@ -0,0 +1,45 @@ +const v = ['a', 'e', 'i', 'o', 'u'] +const check = (str) => { + const map = new Map() + + for (let i = 0; i < str.length; i++) { + if (v.includes(str[i])) { + map.set(str[i], (map.get(str[i]) || 0) + 1) + } + } + + let res = 0 + map.forEach(n => { + res += n + }) + return res +} + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +export const maxVowels = function (s, k) { + let i = 0 + let res = 0 + + const temp = s.slice(i, i + k) + let tmp = check(temp) + res = Math.max(res, tmp) + + while (i + k <= s.length) { + i++ + if (v.includes(s[i + k - 1])) { + tmp++ + } + + if (v.includes(s[i - 1])) { + tmp-- + } + + res = Math.max(res, tmp) + } + + return res +} diff --git a/test/string/maximum-number-of-vowels-in-a-substring-of-given-length.test.js b/test/string/maximum-number-of-vowels-in-a-substring-of-given-length.test.js new file mode 100644 index 0000000..2e35a3a --- /dev/null +++ b/test/string/maximum-number-of-vowels-in-a-substring-of-given-length.test.js @@ -0,0 +1,6 @@ +import { maxVowels } from '../../src/string/maximum-number-of-vowels-in-a-substring-of-given-length' + +test('定长子串中元音的最大数目', () => { + expect(maxVowels('abciiidef', 3)).toBe(3) + expect(maxVowels('rhythms', 4)).toBe(0) +})