题意:有一个序列,第一个数1,后继的是对前一个数的读取输出(统计连续位数出现的次数)。给出一个整数,求序列中的第n个数
思路:用序列生成的定义来做
代码如下:
public class Solution
{
public String countAndSay(int n) {
String s = "1";
for (int i = 2; i <= n; i++) {
StringBuilder tmp = new StringBuilder();
for (int j = 0; j < s.length(); j++) {
int count = 1;
while (j + 1 < s.length() && s.charAt(j) == s.charAt(j + 1)) {
count++;
j++;
}
tmp.append(String.valueOf(count));
tmp.append(s.charAt(j));
}
s = tmp.toString();
}
return s;
}
}