본문 바로가기

Algorithm/LeetCode

LeetCode 38. Count And Say

문제링크: 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

문제 요약: 숫자가 주어질때, 숫자에 대한 String 을 출력. (아래 예제 참고)

예: 1 => "1" (default)

2 => 이전값을 세고, 읽는다. (1을 호출, 한개의 1 => "11")

3 => 이전값(2)을 세고, 읽는다. (2를 호출("11") => 2개의 1 => "21")

4 => 이전값(3)을 세고, 읽는다. (3을 호출("21") => 한개의2 한개의1 => "1211")

...

 

문제 접근: 문제만 이해한다면, 문제를 그대로 반복문으로 풀면 된다. 신경써야할껀 14번째줄 주석 //똑같다면, 이부분과 배열 index 체크정도가 될 듯 하다.

public String countAndSay(int n) {
        String[] dp = new String[n];
        dp[0] = "1";
        for (int i = 1; i < n; i++) {
            StringBuilder builder = new StringBuilder();
            // 이전 값 호출
            String before = dp[i-1];
            for (int j = 0; j < before.length(); j++) {
                char c = before.charAt(j);
                int counter = 1;
                // char 한개씩 읽어서 똑같은게 몇개인지 센다.
                for (int k = j + 1; k < before.length(); k++) {
                    char nextChar = before.charAt(k);
                    // 똑같다면, 루프가 끝나고 이번 index를 건너뛰기 위해서 i값 증가.
                    if (c == nextChar) {
                        j++;
                        counter++;
                    } else {
                        break;
                    }
                }
                builder.append(counter);
                builder.append(c);
            }
            dp[i] = builder.toString();
        }

        return dp[n-1];
    }

dp인줄알고 변수명을 dp로 지었는데 아니었다..

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

LeetCode 83. Remove Duplicates from Sorted List  (0) 2021.01.12
LeetCode 67. Add Binary  (0) 2021.01.11
LeetCode 278. First Bad Version  (0) 2021.01.11
LeetCode 35. Search Insert Position  (0) 2021.01.11
LeetCode 28. Implement strStr()  (0) 2021.01.08