首页 > 其他 > 详细

Leetcode Count and Say

时间:2015-10-10 10:13:22      阅读:157      评论: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.


解题思路:

直观的解题思路,只要把逻辑想清楚,就对了。本题自己想出来了,但是代码不够简洁,参考一些代码后优化如下。用StringBuilder。


Java code:

public String countAndSay(int n) {
        StringBuilder result = new StringBuilder();
        
        for(int i = 0; i < n; i++){
            StringBuilder s = new StringBuilder();
            if(result.length() == 0){
                s.append(1);
            }else{
                int count = 1;
                for(int j = 1; j < result.length(); j++){
                    if(result.charAt(j) == result.charAt(j-1)){
                        count++;
                    }else {
                        s.append(count);
                        s.append(result.charAt(j-1));
                        count = 1;
                    }
                }
                s.append(count);
                s.append(result.charAt(result.length()-1));
            }
            result = s;
        }
        return result.toString();
    }

Reference:

1. http://www.programcreek.com/2014/03/leetcode-count-and-say-java/

 

Leetcode Count and Say

原文:http://www.cnblogs.com/anne-vista/p/4865755.html

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