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.
思路:递归生成字符串,注意字符转字符串需要用String.valueOf()方法。
public class Solution {
public String countAndSay(int n) {
String str = "1";
for (int i = 1; i < n; i++) {
str = solve(str);
}
return str;
}
public String solve(String str) {
String result = "";
char ch = str.charAt(0);
System.out.println(ch);
int count = 1;
for (int i = 1; i < str.length(); i++) {
char c = str.charAt(i);
if (ch == c) {
count++;
} else {
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
ch = c;
count = 1;
}
}
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
return result;
}
}