Skip to content

Commit 299a8b8

Browse files
author
applewjg
committed
CountandSay
Change-Id: Id9ecbf353e2b65df40a69708115d2672b1f14360
1 parent f682fff commit 299a8b8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

CountandSay.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 20, 2014
4+
Problem: Count and Say
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/count-and-say/
7+
Notes:
8+
The count-and-say sequence is the sequence of integers beginning as follows:
9+
1, 11, 21, 1211, 111221, ...
10+
11+
1 is read off as "one 1" or 11.
12+
11 is read off as "two 1s" or 21.
13+
21 is read off as "one 2, then one 1" or 1211.
14+
Given an integer n, generate the nth sequence.
15+
Note: The sequence of integers will be represented as a string.
16+
17+
Solution: ...
18+
*/
19+
20+
public class Solution {
21+
public String countAndSay(int n) {
22+
StringBuffer s = new StringBuffer("1");
23+
StringBuffer res = new StringBuffer();
24+
while((--n) != 0){
25+
res.setLength(0);
26+
int size = s.length();
27+
int cnt = 1;
28+
char cur = s.charAt(0);
29+
for(int i=1;i<size;i++){
30+
if(s.charAt(i)!=cur){
31+
res.append(cnt);
32+
res.append(cur);
33+
cur = s.charAt(i);
34+
cnt = 1;
35+
}else ++cnt;
36+
}
37+
res.append(cnt);
38+
res.append(cur);
39+
StringBuffer tmp = s;
40+
s = res;
41+
res = tmp;
42+
}
43+
return s.toString();
44+
}
45+
}

0 commit comments

Comments
 (0)