[leetcode, JS] 2185. Counting Words With a Given Prefix

mxxn·2023년 12월 15일
0

leetcode

목록 보기
149/198

문제

문제 링크 : 2185. Counting Words With a Given Prefix

풀이

/**
 * @param {string[]} words
 * @param {string} pref
 * @return {number}
 */
var prefixCount = function(words, pref) {
    return words.reduce( (cnt, word) => {
        const prefLeng = pref.length
        const newStr = pref + word.slice(prefLeng)
        if(word === newStr) cnt+=1
        return cnt
    }, 0)
};
  1. 배열 words를 reduce문을 통해 카운팅 계산
  2. pref + word.slice(prefLeng)이 words의 각 element와 같은지 비교
  • Runtime 43 ms, Memory 43.33 MB

다른 풀이

/**
 * @param {string[]} words
 * @param {string} pref
 * @return {number}
 */
var prefixCount = function(words, pref) {
    return words.filter( word => word.startsWith(pref)).length
};
  1. startsWith와 filter를 활용한 풀이
  • Runtime 50 ms, Memory 41.84 MB
profile
내일도 글쓰기

0개의 댓글