Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

38. Count and Say (세고 말하기) C# 본문

코딩 테스트/LeetCode

38. Count and Say (세고 말하기) C#

포카리tea 2022. 10. 19. 18:06
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.

count-and-say 절차는 재귀 공식으로 정의된 일련의 숫자 문자열입니다.

  • countAndSay(1) = "1"
  • countAndSay(n)는 countAndSay(n-1)의 숫자 문자열을 "말하는" 방식이며, 다른 숫자 문자열로 변환됩니다.

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":

숫자 문자열을 "말하는" 방법을 결정하려면 각 하위 문자열에 정확히 하나의 고유한 숫자가 포함되도록 최소 수의 하위 문자열로 분할합니다. 그런 다음 각 하위 문자열에 대해 자릿수를 말한 다음 숫자를 말합니다. 마지막으로 모든 숫자를 연결합니다.

예를 들어 숫자 문자열 "332225"을 변환하고 말하는 것은 다음과 같습니다:

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

양의 정수 n이 주어졌을 때, count-and-say 절차의 nth째 항을 반환하세요.

 

예시 1:

입력: n = 1
출력: "1"
설명: 기본 사례입니다.

예시 2:

입력: n = 4
출력: "1211"
설명:
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"

 

조건:

  • 1 <= n <= 30

정답:

public class Solution {
    
    public string CountAndSay(int n) {
        string s = "1";
        return fuction(n, s);
    }
    
    public static string fuction(int n, string s)
    {
        List<string> sList = new List<string>();

        int splitStart = 0;
        string returnString = "";

        for(int i = 0; i < s.Length; i++)
        {
            if(s[splitStart] != s[i])
            {
                sList.Add(s.Substring(splitStart, i - splitStart));
                splitStart = i;
            }
        }
        sList.Add(s.Substring(splitStart));

        for(int i = 0; i < sList.Count; i++)
        {
            sList[i] = sList[i].Length.ToString() + (sList[i])[0];

            returnString += sList[i];
        }


        if(n >= 2)
            return (fuction(n - 1, returnString));
        else
            return s;
    }
}

해설: 문자열 s의 splitStart 번호를 기준으로 s의 i번째와 비교 후 다르다면 같았던 문자열끼리 sList로 넣어두고 sList 배열 안의 문자열 길이 + 배열 안의 문자열 첫번째 숫자를 문자열로 더한 값을 return 해주었습니다.