Skip to content

Commit 5d6a11d

Browse files
committed
add solution of problem 38: count and say
1 parent 61dd31c commit 5d6a11d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

CountAndSay38/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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+
Given an integer *n*, generate the n<sup>th</sup> sequence.
8+
9+
Note: The sequence of integers will be represented as a string.

CountAndSay38/Solution.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class Solution {
2+
public String countAndSay(int n) {
3+
String last = "1";
4+
5+
for (int i = 1; i < n; i++) {
6+
StringBuilder sb = new StringBuilder();
7+
int j = 0;
8+
while (j < last.length()) {
9+
int cnt = 1;
10+
11+
while (j + 1 < last.length() && last.charAt(j + 1) == last.charAt(j)) {
12+
j++;
13+
cnt++;
14+
}
15+
16+
sb.append(cnt).append(last.charAt(j));
17+
j++;
18+
}
19+
20+
last = sb.toString();
21+
}
22+
23+
return last;
24+
}
25+
}

0 commit comments

Comments
 (0)