-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCountAndSay.java
34 lines (29 loc) · 925 Bytes
/
CountAndSay.java
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
30
31
32
33
34
package leetcode;
public class CountAndSay {
public String countAndSay(int n) {
if (n <= 0) {
return "";
} else if (n == 1) {
return "1";
} else if (n == 2) {
return "11";
}
StringBuilder builder = new StringBuilder();
char[] previous = countAndSay(n - 1).toCharArray();
int currentCount = 1;
for (int i = 1; i < previous.length; i++) {
if (previous[i] == previous[i - 1]) {
currentCount++;
} else {
builder.append(Integer.toString(currentCount));
builder.append(previous[i - 1]);
currentCount = 1;
}
}
if (currentCount != 0) {
builder.append(Integer.toString(currentCount));
builder.append(previous[previous.length - 1]);
}
return builder.toString();
}
}