原题链接在这里:https://leetcode.com/problems/count-and-say/
当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个。
从i = 2开始一直到n作为外层loop, i是第 ith 个结果。
进入循环后,新生成count = 1, index = 1, 然后进入内层loop, 用index 从第二位走res, 现字符等同于前字符就count++, 不同字符就先append count, 然后 append 前字符,然后count归为1. 走完内层loop, 再把最后一段的count, 字符加到StringBuilder中。
Note: count, StringBuikder,index 都需要在外层循环归回原数。
AC Java:
public class Solution {
public String countAndSay(int n) {
if(n<=0){
return "";
}
if(n==1){
return "1";
}
String res = "1";
for(int i = 2; i<=n; i++){
int count = 1;
StringBuilder sb = new StringBuilder();
int index = 1;
for( index = 1; index<res.length(); index++){
if(res.charAt(index) == res.charAt(index-1)){
count++;
}else{
sb.append(count);
sb.append(res.charAt(index-1));
count = 1;
}
}
sb.append(count);
sb.append(res.charAt(index-1));
res = sb.toString();
}
return res;
}
}