首页 > 其他 > 详细

Leetcode#38Count and Say

时间:2015-05-05 19:56:42      阅读:140      评论: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.

分析,迭代求解第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

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

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