The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.11
is read off as "two 1s"
or 21
.21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
public class Solution { public String countAndSay(int n) { //本题主要需要理解题意,声明两个变量count和last,每次向res中添加的是count+last,count代表有几个相同的字符以及last代表最后一个字符是
//什么,res代表上一个字符串序列 //需要注意的是第一层循环的范围,从1开始,以及最后一位时需要保存住信息。 if(n==1) return "1";//当为1时,直接返回 String result="1"; for(int i=1;i<n;i++){//注意i的范围 StringBuilder res=new StringBuilder(); int count=1; char last=result.charAt(0); for(int j=1;j<result.length();j++){ if(result.charAt(j)==last){ count++; }else{ res.append(count); res.append(last); count=1; last=result.charAt(j); } } res.append(count);//最后一位需要保存 res.append(last); result=res.toString(); } return result; } }