[LeetCode] Check if Number Has Equal Digit Count and Digit Value

준규·2023년 3월 5일
0

1.문제


You are given a 0-indexed string num of length n consisting of digits.

Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.


index가 0부터 시작하는 문자열 num이 주어질 때 모든 num의 digit이 num[i] (0 <= i < n) 번 나타나면 true , 아니라면 false를 리턴하는 문제이다.


Example 1

Input: num = "1210"
Output: true
Explanation:
num[0] = '1'. The digit 0 occurs once in num.
num[1] = '2'. The digit 1 occurs twice in num.
num[2] = '1'. The digit 2 occurs once in num.
num[3] = '0'. The digit 3 occurs zero times in num.
The condition holds true for every index in "1210", so return true.

Example 2

Input: num = "030"
Output: false
Explanation:
num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
num[2] = '0'. The digit 2 occurs zero times in num.
The indices 0 and 1 both violate the condition, so return false.

Constraints:

  • n == num.length
  • 1 <= n <= 10
  • num consists of digits.

2.풀이

  1. num의 각 digit의 개수를 map에 저장한다.
  2. 반복문을 돌면서 각 digit이 num[i]의 값만큼의 개수인지를 체크한다.

/**
 * @param {string} num
 * @return {boolean}
 */
const digitCount = function (num) {
  let map = {};
  let result = true;

  // digit의 개수를 체크해서 map에 저장
  for (let i = 0; i < num.length; i++) {
    map[num[i]] ? (map[num[i]] = map[num[i]] + 1) : (map[num[i]] = 1);
  }

  for (let i = 0; i < num.length; i++) {
    const digitTimes = parseInt(num[i]);

    // digit의 갯수와 num[i]의 값이 같은지 체크한다
    if (digitTimes !== map[i]) {
      if (digitTimes === 0 && map[i] === undefined) {
        result = true;
      } else {
        result = false;
        break;
      }
    }
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글