Problem
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.
Note
用递归做这种找规律的题目。用stringbuilder。遍历递归而来的字符串s,当前字符与上一个相同时,只计数;不同时,添加计数和字符,然后重设计数和字符。
Solution
Recursion
public class Solution {
public String countAndSay(int n) {
if (n == 0) return "";
if (n == 1) return "1";
String s = countAndSay(n-1);
char ch = s.charAt(0);
int count = 1;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == ch) count++;
else {
sb.append(count);
sb.append(ch);
count = 1;
ch = s.charAt(i);
}
}
sb.append(count);
sb.append(ch);
return sb.toString();
}
}
DP
class Solution {
public String countAndSay(int n) {
if (n <= 0) return "";
String[] dp = new String[n+1];
dp[0] = "";
dp[1] = "1";
for (int i = 2; i <= n; i++) {
StringBuilder sb = new StringBuilder();
char ch = dp[i-1].charAt(0);
int count = 1;
for (int j = 1; j < dp[i-1].length(); j++) {
if (ch == dp[i-1].charAt(j)) count++;
else {
sb.append(count).append(ch);
count = 1;
ch = dp[i-1].charAt(j);
}
}
sb.append(count).append(ch);
dp[i] = sb.toString();
}
return dp[n];
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。