본문 바로가기
IT/LeetCode

[LeetCode] 38. Count and Say

by 강천구 2022. 7. 22.

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

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"

 

Constraints:

  • 1 <= n <= 30

주어진 숫자에서 각 숫자가 몇번 나오는지 체크하여 다음 숫자를 만드는 구조를 input으로 받은 n번 진행했을 때의 결과를 구하는 문제이다.

n번 만큼 반복을 while을 이용하였고, 각 문장에서 특정 숫자가 몇 번 나오는지 for문을 이용하여 체크하는 방식으로 진행했다.

 

class Solution:
   def countAndSay(self, n):
       if n == 1:
           return "1"
       else:
           n -= 1
           answer = "1"
           count = 0
           while count < n :
               now = ""
               nowNum = 0
               nowCount = 0
               for i in range(0, len(answer)):
                   if answer[i] == nowNum:
                       nowCount += 1
                   else :
                       if nowNum != 0:
                           now += nowCount.__str__() + nowNum.__str__()
                       nowNum = answer[i]
                       nowCount = 1
               now += nowCount.__str__() + nowNum.__str__()
               answer = now
               count += 1
           return answer

 

 

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

 

Count and Say - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_38.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 58. Length of Last Word  (0) 2022.08.15
[LeetCode] 53. Maximum Subarray  (0) 2022.08.15
[LeetCode] 35. Search Insert Position  (0) 2022.07.22
[LeetCode] 28. Implement strStr()  (0) 2022.07.22
[Leetcode] 27. Remove Element  (0) 2022.07.22

댓글