forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-and-say.java
More file actions
35 lines (30 loc) · 885 Bytes
/
count-and-say.java
File metadata and controls
35 lines (30 loc) · 885 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
30
31
32
33
34
35
// Count and Say
// @author 连城 (http://weibo.com/lianchengzju)
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public String countAndSay(int n) {
String s = "1";
while (--n > 0)
s = getNext(s);
return s;
}
String getNext(final String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length();) {
int j = notEqual(s, i);
sb.append(j - i);
sb.append(s.charAt(i));
i = j;
}
return sb.toString();
}
// find the first char that not equal to fromIndex
private static int notEqual(final String s, int fromIndex) {
final char target = s.charAt(fromIndex);
int i = fromIndex;
for (; i < s.length(); ++i) {
if (s.charAt(i) != target) break;
}
return i;
}
}