-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_38.java
More file actions
29 lines (26 loc) · 809 Bytes
/
Copy pathP_38.java
File metadata and controls
29 lines (26 loc) · 809 Bytes
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
29
package leetcode.easy;
public class P_38 {
static final String[] dp = new String[30];
public String countAndSay(int n) {
if (dp[n - 1] != null) {
return dp[n - 1];
}
dp[0] = "1";
for (int i = 1; i < dp.length; i++) {
final StringBuilder sb = new StringBuilder();
final String prev = dp[i - 1];
int j = 0;
while (j < prev.length()) {
final int start = j;
final char currNum = prev.charAt(j);
while (j < prev.length() && currNum == prev.charAt(j)) {
j++;
}
sb.append(j - start);
sb.append(currNum);
}
dp[i] = sb.toString();
}
return dp[n - 1];
}
}