forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountAndSay.java
37 lines (31 loc) · 869 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
35
36
37
public class CountAndSay {
public String countAndSay(int n) {
String s = "1";
for (int i = 2; i <= n; i++) {
s = next(s);
}
return s;
}
private String next(String s) {
StringBuilder sb = new StringBuilder();
char cur = 0;
int times = 0;
for (int i = 0; i < s.length(); i++) {
if (times == 0) {
cur = s.charAt(i);
times = 1;
} else if (s.charAt(i) == cur) {
times++;
} else {
sb.append(String.format("%d%c", times, cur));
cur = s.charAt(i);
times = 1;
}
}
// 这一句千万别掉了
if (times != 0) {
sb.append(String.format("%d%c", times, cur));
}
return sb.toString();
}
}