[LeetCode] countAndSay

一道比较有意思的水题。

题目

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.

意思就是后面的一个数字是对前面的数字的一个表示。

老规矩,上代码

public class Solution {

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

 

posted @ 2015-12-19 00:35  hudiwei-hdw  阅读(177)  评论(0编辑  收藏  举报