Leetcode: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.
後一個數則是把前一個數和數字的個數一起讀出來。
如第二個:一個1。於是就是11
第三個:兩個1,於是 21
第四個:一個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();
    }

實現不是很好

發佈了88 篇原創文章 · 獲贊 5 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章