[LeetCode] Count Asterisks

준규·2023년 1월 3일
0

1.문제


You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.

Return the number of '*' in s, excluding the '*' between each pair of '|'.

Note that each '|' will belong to exactly one pair.


문자열 s가 주어지는 데 s 문자열은 '|'을 포함하고 있고, 1번째 '|'와 2번째 '|'가 pair를 이루고 3번째 '|'와 4번째 '|'가 pair를 이루는 규칙을 가진다고 한다.

이런 조건에서 '|'의 pair 를 제외한 나머지 그룹에서 '*'의 갯수를 리턴하는 문제이다.


Example 1

Input: s = "l|*e*et|c**o|*de|"
Output: 2
Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|".
The characters between the first and second '|' are excluded from the answer.
Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.

Example 2

Input: s = "iamprogrammer"
Output: 0
Explanation: In this example, there are no asterisks in s. Therefore, we return 0.

Example 3

Input: s = "yo|uar|e**|b|e***au|tifu|l"
Output: 5
Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
  • s contains an even number of vertical bars '|'.

2.풀이

  1. s를 '|' 기준으로 잘라서 배열에 넣는다.
  2. 배열의 홀수 index의 단어는 pair에 속하는 단어이므로 체크하지 않는다.
  3. 단어안에 '*'가 포함되는지 체크한다.
  4. 포함된다면 '*'의 갯수를 체크한다.

/**
 * @param {string} s
 * @return {number}
 */
const countAsterisks = function (s) {
  let result = 0;
  // '|' 기준으로 단어 나눠주기
  s = s.split("|");
  // index 0 부터 짝수 index의 단어들만 검사한다.
  for (let i = 0; i < s.length; i += 2) {
    // 현재 단어에 '*' 이 포함 되어있다면
    if (s[i].includes("*")) {
      // 그 단어에 포함되어있는 '*'의 갯수를 체크한다
      for (let j = 0; j < s[i].length; j++) {
        if (s[i][j] === "*") result++;
      }
    }
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글