Count and Say

Count and Say

https://leetcode.com/problems/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.

算法思想:

  1. 可以根据当前的这个string,来计算下一个string,如“1211”,得到“one 1 one 2 two 1”,即"111221"

程序代码:


public class Solution {

    public String next(String s) {

        int length = s.length();

        char pre = s.charAt(0);

        int count = 1;

        StringBuilder sb = new StringBuilder();

        for (int i = 1; i < length; i++) {

            if (s.charAt(i) == pre) {

                count++;

            } else {

                sb.append(count);

                sb.append(pre);

                count = 1;

                pre = s.charAt(i);

            }

        }

        sb.append(count);

        sb.append(pre);

        

        return sb.toString();

    }

    

    public String countAndSay(int n) {

        if (n <= 0) {

            return "";

        }

        

        String cas = "1";

        for (int i = 2; i <= n; i++) {

            cas = next(cas);

        }

        return cas;

    }

}


posted @ 2015-08-25 14:09  TinaYo  阅读(168)  评论(-1编辑  收藏  举报