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

[LeetCode] countAndSay

时间:2015-12-19 01:26:36      阅读:248      评论: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.

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

老规矩,上代码

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();
    }
    }

 

[LeetCode] countAndSay

标签:

原文地址:http://www.cnblogs.com/dick159/p/5058537.html

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