给定1然后2是读出1的内容,以此类推。
1 = 1;
2 = 11;
3 = 21;
4 = 1211;
5 = 111221;
题目有点难理解,代码还是比较好写的。效率待优化,因为要不断地拼接数据,所以用StringBuilder比较好一点。
public String countAndSay(int n) {
String[] strings = new String[n];
strings[0] = "1";
for (int i = 1; i < n; i++) {
StringBuilder builder = new StringBuilder("");
for (int j = 0; j < strings[i - 1].length(); j++) {
char a = strings[i - 1].charAt(j);
int num = 1;
while (j < strings[i - 1].length() - 1 && strings[i - 1].charAt(j + 1) == a){
num++;
j++;
}
builder.append(String.valueOf(num) + strings[i - 1].charAt(j));
}
strings[i] = builder.toString();
}
return strings[n - 1];
}