LeetCode 코딩 문제 2021/06/17 - Count and Say

이호현·2021년 6월 17일
0

Algorithm

목록 보기
124/138

[문제]

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

(요약) 주어진 문자열 숫자를 개수, 숫자, 개수, 숫자, ...가 되도록 n번 반복했을 때 return값 구하기 (문제는 이해하기 쉬운데 말로 설명하기가 까다롭네)

[풀이]

var countAndSay = function(n) {
  let answer = '1';

  for(let i = 0; i < n - 1; i++) {
    answer = change(answer);
  }

  return answer;
};

function change(num) {
  const str = num + '';
  const arr = [[0, str[0]|0]];
  let index = 0;
 
  for(let i = 0; i < str.length; i++) {
    if(arr[index][1] !== (str[i]|0)) {
      arr.push([1, str[i]|0]);
      index++;
    }
    else {
      arr[index][0]++;
    }
  }

  return arr.flat().join('');
}

기본값을 1로 하고, n - 1번 반복한다.

반복하는 내용은 현재 숫자로 된 문자열을 앞에서부터 같은 것의 개수를 다른 숫자가 나올 때까지 세고, 바뀐 숫자를 또 다른 숫자가 나올 때까지 세고, 반복해서 새로운 문자열을 만들면 된다.

이전에 같은 숫자가 나왔어도 카운트는 새로 시작한다.

flat()으로 배열 요소들을 펼칠 때 새로 정렬 안해도 되게끔 2차원 배열을 만들고, [개수, 숫자]의 형식으로 담았다.

profile
평생 개발자로 살고싶습니다

0개의 댓글