leetcode 0038
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
用dp做,一个一个往下推。
下一个数的生成方法是:按顺序记录相同数的出现次数,先描述出现个数,在描述数字本身,直至将数字推完。
class Solution {
public String countAndSay(int n) {
String[] dp = new String[30];
dp[0] = "1";
for (int i = 1; i < n; i++) {
dp[i] = nextString(dp[i - 1]);
}
return dp[n - 1];
}
public String nextString(String now) {
if (now.length() == 1) {
return "1" + now;
}
StringBuilder next = new StringBuilder();
int count = 1;
for (int i = 1; i < now.length(); i++) {
if (now.charAt(i) == now.charAt(i - 1)) {
count++;
} else {
next.append(count);
next.append(now.charAt(i - 1));
count = 1;
}
if (i == now.length() - 1) {
next.append(count);
next.append(now.charAt(i));
}
}
return next.toString();
}
}