[M] 38. Count and Say

YJ·6일 전

leetcode

목록 보기
76/100

https://leetcode.com/problems/count-and-say

문제

countAndSay(n) 을 구하는 문제..

답안

public String countAndSay(int n) {
	String[] memo = new String[n + 1];
	memo[1] = "1";
	for (int i = 2; i <= n; i ++) {
		memo[i] = countAndSay(memo[i - 1]);
	}
	return memo[n];
}

public String countAndSay(String str) {
	StringBuilder sb = new StringBuilder();
	int i = 0;
	while (i < str.length()) {
		char digit = str.charAt(i);
		int count = 0;
		while (i < str.length() && str.charAt(i) == digit) {
			count++;
			i++;
		}
		sb.append(count).append(digit);
	}
	return sb.toString();
}

메모

이런 String 안에서 pointer 로 움직여야 하는 구현들이 은근히 어렵다..
포인터가 무얼 가리키는지, 언제 멈춰야 하는지부터 생각할 것.
언제까지 반복해야 하고, 반복할 때마다 무엇이 바뀌는지 생각할 것.

  • 이 문제에서 i는 아직 처리하지 않은 다음 문자를 가리킨다.
  • 먼저 전체 문자열을 처리하는 반복문이 필요하고 (while (i < str.length()))
  • 그리고 현재 문자와 같은 숫자가 계속 등장하는지 확인해야 한다.
profile
Hello

0개의 댓글