Leetcode:Count and Say

2675 ワード

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です.次の数は、前の数と数字の数を一緒に読みます.2つ目:1つ1.そこで11番目の3つ:2つの1、そこで21番目の4つ:1つの2、1.そして1211はこう推す
toSay関数を書きます.そして入力stringごとにsay形式の出力を出力します.
その後、n回繰り返し呼び出せばよい.
重要なのは、いくつかの連続するx(x=1-9)を統計し、int個数を得た後、文字列に変換して接続することである.
    public static String countAndSay(int n) {
        if(n==0) return "";
        if(n==1) return "1";
        if(n==2) return "11";
        int a=2;
        String temp="11";
        while(a++!=n){
            temp=toSay(temp);
        }
        return temp;
    }
    public static String toSay(String s){
        char temp=s.charAt(0);
        int count=0;
        StringBuffer result= new StringBuffer();
        for(int i=0;i<s.length();i++){
            if(temp==s.charAt(i)) count++;
            else {
                result.append(count);
                count=1;
                result.append(temp);
                temp=s.charAt(i);
            }
        }
        result.append(count);
        result.append(s.charAt(s.length()-1));
        return result.toString();
    }

うまくいかない