Leetcode Count and Say

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/

 

posted @ 2015-10-10 09:10  茜茜的技术空间  阅读(158)  评论(0编辑  收藏  举报