본문 바로가기
LeetCode

[LeetCode] 38. Count and Say

by JungSeung 2023. 11. 2.
728x90

https://leetcode.com/

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 substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

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

출처 : https://leetcode.com/problems/count-and-say/description/

Given a positive integer n, return the n^th 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"

 

Constraints:

  • 1 <= n <= 30

 

Code :

var countAndSay = function(n) {
    if (n === 1) return "1"; // n이 1인 경우 1을 반환

    let result = "1"; // 결과를 1로 초기화
    for (let i = 2; i <= n; i++) { // 2부터 n까지 반복
        result = say(result); // say 함수를 통해 결과값 갱신
    }

    return result; // 결과 반환
};

var say = function(str){
    let result = ""; // 결과값 초기화
    let count = 1; // 카운트 초기화

    for (let i = 0; i < str.length; i++) { // 문자열의 길이만큼 반복
        if (str[i] === str[i + 1]) { // 현재 문자와 다음 문자가 같으면 카운트 증가
            count++;
        } else { // 현재 문자와 다음 문자가 다르면 결과값에 카운트와 문자를 추가하고 카운트는 1로 재설정
            result += count + str[i];
            count = 1;
        }
    }

    return result; // 결과 반환
};

 

Solutions Code :

var countAndSay = function(n) {
    if (n === 1) return '1'; // n이 1일 때 '1'을 반환

    return countAndSay(n-1) // n-1에 대한 countAndSay 호출 후
        .match(/1+|2+|3+/g) // 숫자들을 그룹화하여 배열로 추출
        .reduce((acc, nums) => acc += `${nums.length}${nums[0]}`, ''); // 각 그룹의 길이와 첫 번째 숫자를 합쳐 결과 생성
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 40. Combination Sum II  (0) 2023.11.06
[LeetCode] 39. Combination Sum  (0) 2023.11.03
[LeetCode] 37. Sudoku Solver  (0) 2023.11.02
[LeetCode] 36. Valid Sudoku  (0) 2023.11.02
[LeetCode] 35. Search Insert Position  (0) 2023.11.01