38. Count and Say

StringBuilder (my solution)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public String countAndSay(int n) {
String result = "1";
while (n > 1) {
result = helper(result);
n--;
}
return result;
}

private String helper(String s) {
int n = s.length();
int pos = 0;
StringBuilder sb = new StringBuilder();
while (pos < n) {
char c = s.charAt(pos);
int cnt = 1;
while ((pos + 1 < n) && s.charAt(pos + 1) == c) {
cnt++;
pos++;
}
sb.append(String.valueOf(cnt));
sb.append(c);
pos++;
}
return sb.toString();
}
}

Remarks:

  1. TC: $O(2^n)$
  2. Don’t forget to pos++ at the end of the while loop
  3. In the while statement, first check pos + 1 < n then check s.charAt(pos + 1).
    Java handles logic expression LEFT to RIGHT.