码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#38Count and Say

时间:2015-05-05 19:57:10      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:beginning   sequence   generate   return   public   

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.

分析,迭代求解第n次时的结果,因此从第一次"1"开始迭代,将上次得到的结果字符串以上述形式重新表述

public class Solution {

    public String countAndSay(int n) {

        

        if(n == 1){  

            return "1";  

        }  

          

        String s = "1";  

        StringBuffer ret = new StringBuffer();  

        int cnt = 0;  

        int round = 0;          // round是迭代多少次  

        int i;  

        while(++round < n){  

            cnt = 1;  

            ret.setLength(0);  

            for(i=1; i<s.length(); i++){  

                if(s.charAt(i) == s.charAt(i-1)){       // 重复的值,继续计数  

                    cnt++;  

                }else{          // 有新的值出现,记录到ret  

                    ret.append(cnt).append(s.charAt(i-1));  

                    cnt = 1;        // 重置cnt  

                }  

            }  

            ret.append(cnt).append(s.charAt(i-1));  

            s = ret.toString(); // 更新s  

        }

        

        return ret.toString();

        

    }

}


Leetcode#38Count and Say

标签:beginning   sequence   generate   return   public   

原文地址:http://7061299.blog.51cto.com/7051299/1642143

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!