LeetCode 38. Count and Say 报数(Java)
程序员文章站
2022-07-15 12:29:50
...
题目:
The count-and-say sequence is the sequence of integers with the first five terms as following:
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note:
Each term of the sequence of integers will be represented as a string.
解答:
用递归的思想,直接循环推出即可
先递归调用countAndSay(n-1),之后对获取到的字符串进行解析,循环这个字符串的长度,每次与上一个字符判断是否相同,相同,则count++,否则在结果中插入count和pre,然后重置count和pre。
class Solution {
public String countAndSay(int n) {
if(n==1){
return "1";
}
String pre=countAndSay(n-1);
StringBuffer sb=new StringBuffer();
char ch=pre.charAt(0);
int count=1;
for(int i=1;i<pre.length();i++){
if(ch==pre.charAt(i)){
count++;
}else{
sb.append(""+count+ch);
ch=pre.charAt(i);
count=1;
}
}
sb.append(""+count+ch);
return sb.toString();
}
}