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()))