計數和表述

原題

  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.算法

題目大意

  n=1時輸出字符串1;n=2時,數上次字符串中的數值個數,由於上次字符串有1個1,因此輸出11;n=3時,因爲上次字符是11,有2個1,因此輸出21;n=4時,因爲上次字符串是21,有1個2和1個1,因此輸出1211。依次類推,寫個countAndSay(n)函數返回字符串。app

解題思路

  第一種狀況:n<0時返回null。
  第二種狀況:當n=1時,返回1
  第三種狀況:當n>1時,假設n-1返回的字符串是s,對s的串進行處理理,對不一樣的數字進行分組好比112365477899,分紅11,2,3,6,5,4,77,8,99。最有就2個1,1個2,1個3,1個6,1個5,一個4,2個7,1個8,2個9,就是211213161614271829,返回此結果。函數

代碼實現

算法實現類ui

public class Solution {
    public String countAndSay(int n) {

        if (n < 1) {
            return null;
        }

        String result = "1";
        for (int i = 2; i <=n ; i++) {
            result = countAndSay(result);
        }

        return result;
    }

    public String countAndSay(String str) {
        StringBuilder builder = new StringBuilder(128);

        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == str.charAt(i - 1)) {
                count++;
            } else {
                builder.append(count);
                builder.append(str.charAt(i - 1));
                count = 1;
            }
        }

        builder.append(count);
        builder.append(str.charAt(str.length() - 1));
        return builder.toString();
    }
}
相關文章
相關標籤/搜索