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

Count And Say

时间:2014-11-21 10:20:56      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   strong   

Problem

Implement Count And Say function. For example, first, let user input a number, say 1. Then, the function will generate the next 10 numbers which satisfy this condition: ,1, 11,21,1211,111221,312211...
explanation: first number 1, second number is one 1, so 11. Third number is two 1(previous number), so 21. next number one 2 one 1, so 1211 and so on...

Solution

public String countAndSay(int n) {
    if (n <= 0)
        return "";

    String curRes = "1";
    int start = 1;

    while (start < n) {
        StringBuffer sb = new StringBuffer();
        int cnt = 1;
        for (int i = 1; i < curRes.length(); i++) {
            if (curRes.charAt(i) == curRes.charAt(i - 1)) {
                cnt++;
            }
            else {
                sb.append(cnt);
                sb.append(curRes.charAt(i - 1));
                cnt = 1;
            }
        }
        sb.append(cnt);
        sb.append(curRes.charAt(curRes.length() - 1));
        curRes = sb.toString();
        start++;
    }

    return curRes;
}

 

Count And Say

标签:style   blog   io   ar   color   os   sp   for   strong   

原文地址:http://www.cnblogs.com/superbo/p/4112146.html

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