首页 > 其他 > 详细

[leedcode 38] Count and Say

时间:2015-07-10 15:02:27      阅读:56      评论:0      收藏:0      [点我收藏+]

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; } }

 

[leedcode 38] Count and Say

原文:http://www.cnblogs.com/qiaomu/p/4635602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!