본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 38] Count and Say

by m2162003 2020. 11. 8.

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"

 

문제 풀이:

앞에서부터 차례대로 1이 하나 2가 두개 1이 세 개... 이런 식으로 붙이는 문제다.

n=1일 때만 "1"을 리턴하고 2부터는 이전 문자열을 불러서 가공한다.

 

++ 자바에서 문자열 concat을 해야 한다면 String보다는 StringBuffer나 StringBuilder를 사용하자.

'+' 연산시 비용이 크기 때문이다. StringBuilder를 사용한다면 마지막에 toString()으로 바꿔주자.

novemberde.github.io/2017/04/15/String_0.html

 

Khbyun's blog

Novemberde's dev

novemberde.github.io

class Solution {
    public String countAndSay(int n) {
        
        if(n==1){
            return "1";
        }
        
        String tmp = countAndSay(n-1);
        StringBuilder result = new StringBuilder();

        int num = 1;
        char prev = tmp.charAt(0);
        for(int i=1; i<tmp.length(); i++){
            if(tmp.charAt(i) == prev){
                num++;
            }else {
                result.append(num).append(prev);
                num = 1;
                prev = tmp.charAt(i);
            }
        }
        result.append(num).append(prev);
        
        return result.toString();
    }
}

댓글