LeetCode & Q38-Count and Say-Easy

String

Description:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

个人觉得这个题意实在是反人类!!!

在此说明一下题意:

例如,5对应111221,6的结果就是对应读5得到的,也就是3个1、2个2、1个1,即:312211

my Solution:

public class Solution {
    public String countAndSay(int n) {
        StringBuffer sb = new StringBuffer("1");
        for (int i = 1; i < n; i++) {
            StringBuffer next = new StringBuffer();
            int count = 1;
            for (int j = 0; j < sb.length(); j++) {
                if (j+1 < sb.length() && sb.charAt(j) == sb.charAt(j+1)) {
                    count++;
                } else {
                    next.append(count).append(sb.charAt(j));
                    count = 1;
                }
            }
            sb = next;
        }
        return sb.toString();
    }
}
posted @ 2017-07-31 14:25  6002  阅读(118)  评论(0编辑  收藏  举报