add: 定长子串中元音的最大数目

This commit is contained in:
yi-ge 2020-05-24 12:38:29 +08:00
parent 5c5f35c535
commit c371738884
4 changed files with 56 additions and 0 deletions

View File

@ -6,6 +6,7 @@
"Paddr",
"Prinme",
"abcdefg",
"abciiidef",
"cdefgab",
"chuan",
"defang",

View File

@ -113,6 +113,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 5416. 检查单词是否为句中其他单词的前缀 <https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/>
- [定长子串中元音的最大数目](src/string/maximum-number-of-vowels-in-a-substring-of-given-length.js)
- LeetCode 5417. 定长子串中元音的最大数目 <https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/>
## 数组/队列/集合/映射
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)

View File

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

View File

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