Skip to content

Latest commit

 

History

History
48 lines (40 loc) · 1.06 KB

2185.统计包含给定前缀的字符串.md

File metadata and controls

48 lines (40 loc) · 1.06 KB

2185.统计包含给定前缀的字符串

/*
 * @lc app=leetcode.cn id=2185 lang=typescript
 *
 * [2185] 统计包含给定前缀的字符串
 */

// @lc code=start
function prefixCount(words: string[], pref: string): number {}
// @lc code=end

解法 1: 枚举

function prefixCount(words: string[], pref: string): number {
  let res = 0
  next: for (let word of words) {
    if (word.length < pref.length) continue
    for (let i = 0; i < pref.length; i++) {
      if (pref[i] !== word[i]) continue next
    }
    res++
  }
  return res
}

解法 2: API

function prefixCount(words: string[], pref: string): number {
  return words.filter(word => word.indexOf(pref) === 0).length
}

Case

test.each([
  { input: { words: ['pay', 'attention', 'practice', 'attend'], pref: 'at' }, output: 2 },
  { input: { words: ['leetcode', 'win', 'loops', 'success'], pref: 'code' }, output: 0 },
])('input: words = $input.words, pref = $input.pref', ({ input: { words, pref }, output }) => {
  expect(prefixCount(words, pref)).toEqual(output)
})