p38

LeetCode p38 Count and Say 题解

1.题目:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

题意:

按规律返回第n个数

2.解题思路:

模拟整个流程 见代码

3.代码


[title] [] [url] [link text]
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
 
public class Solution {
public String countAndSay(int n) {
String aString = "1";
for (int x = 1; x < n; x++) {
StringBuilder stringBuilder = new StringBuilder();
int count = 1;
char c = aString.charAt(0);
for (int i = 1; i < aString.length(); i++) {
if (aString.charAt(i) == c) {
count++;
continue;
}
char a = (char) (count + '0');
stringBuilder.append(a);
stringBuilder.append(c);
count = 1;
c = aString.charAt(i);

}
char a = (char) (count + '0');
stringBuilder.append(a);
stringBuilder.append(c);
aString = stringBuilder.toString();
}
return aString;
}
}

4.一些总结: