Skip to content

Commit 03ed140

Browse files
committed
Count And Say
1 parent 6df7ba5 commit 03ed140

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Count and Say.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
The count-and-say sequence is the sequence of integers beginning as follows:
2+
1, 11, 21, 1211, 111221, ...
3+
4+
1 is read off as "one 1" or 11.
5+
11 is read off as "two 1s" or 21.
6+
21 is read off as "one 2, then one 1" or 1211.
7+
8+
Given an integer n, generate the nth sequence.
9+
10+
Note: The sequence of integers will be represented as a string.
11+
12+
public class Solution {
13+
public String countAndSay(int n) {
14+
StringBuilder s1 = new StringBuilder("1");
15+
StringBuilder s2 = new StringBuilder();
16+
for (int i = 1; i < n; i++) {
17+
int j = 0;
18+
int len = s1.length();
19+
while (j < len) {
20+
int count = 1;
21+
char c = s1.charAt(j);
22+
while (j < len - 1 && s1.charAt(j + 1) == s1.charAt(j)) {
23+
count++;
24+
j++;
25+
}
26+
s2.append(count + "");
27+
s2.append(c);
28+
if (j == len - 1) {
29+
break;
30+
}
31+
j++;
32+
}
33+
s1 = s2;
34+
s2 = new StringBuilder();
35+
}
36+
return s1.toString();
37+
}
38+
}

0 commit comments

Comments
 (0)