[LeetCode] Count Prefixes of a Given String

준규·2023년 2월 7일
0

1.문제


You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.

Return the number of strings in words that are a prefix of s.

A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.


문자열이 들어있는 배열 words와 문자열 s 가 주어질 때 words에서 s의 prefix에 해당하는 단어의 갯수를 리턴하면 되는 문제이다.


Example 1

Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.

Example 2

Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s. 
Note that the same string can occur multiple times in words, and it should be counted each time.

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, s.length <= 10
  • words[i] and s consist of lowercase English letters only.

2.풀이

  1. s의 알파벳을 앞에서부터 잘라서 prefix 배열을 만든다.
  2. words 배열의 단어중 prefix 배열에 들어있는 단어의 개수를 체크한다.

/**
 * @param {string[]} words
 * @param {string} s
 * @return {number}
 */
const countPrefixes = function (words, s) {
  const prefix = [];
  let count = 0;
  // s 를 prefix 배열에 잘라서 넣는다
  for (let i = 1; i <= s.length; i++) {
    prefix.push(s.substring(0, i));
  }

  // words 배열에서 prefix에 해당하는 단어의 갯수를 센다
  words.forEach((char) => {
    if (prefix.includes(char)) count++;
  });

  return count;
};

3.결과

profile
안녕하세요 :)

0개의 댓글