题目描述
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1
11
21
1211
111221
1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
题目的意思是对序列前一个数进行报数,数列第一项不是1吗,那第二项就报第一项的有1个1,输出11,然后第三项就在第二项的基础上报数,第二项是11,第三项不就是2个1么,然后输出21。。。
总结
递归得到需要报的数,然后即easy了
Sample & Demo Code
class Solution {
public String countAndSay(int n) {
if(n == 1) return "1";
String input = countAndSay(n-1);
StringBuilder res = new StringBuilder();
for(int i = 0; i < input.length(); i++) {
int curTimes = 1;
char curDigit = input.charAt(i);
for(int j = i+1; j < input.length(); j++) {
if(input.charAt(j) == curDigit) curTimes++;
else break;
}
res.append(curTimes).append(curDigit);
i += curTimes-1;
}
return res.toString();
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-and-say