forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCountandSay.java
49 lines (46 loc) · 1.08 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : CountandSay
* Creator : Edward
* Date : Oct, 2017
* Description : 38. Count and Say
*/
public class CountandSay {
/**
1. 1
2. 11
3. 21
4. 1211
5. 111221
time : 不知道
space : O(n)
* @param n
* @return
*/
public String countAndSay(int n) {
int i = 1;
String res = "1";
while (i < n) {
int count = 0;
StringBuilder sb = new StringBuilder();
char c = res.charAt(0);
for (int j = 0; j <= res.length(); j++) {
if (j != res.length() && res.charAt(j) == c) {
count++;
} else {
sb.append(count);
sb.append(c);
if (j != res.length()) {
count = 1;
c = res.charAt(j);
}
}
}
res = sb.toString();
i++;
}
return res;
}
}