這一道題目,很相似於小學的問題,可是若是硬是要將輸入和結果產生數值上的聯繫就會產生混亂了,所以咱們要打破思惟定勢。java
這道題最難的實際上是理解,由於描述的不盡其意,因此很難理解,其實就是根據最開始的字符串,不斷的擴展,輸入的N,表明的是通過N次以後的結果,與其中的結果沒有任何關係。app
1 /** 2 * 題目大意 3 * n=1時輸出字符串1;n=2時,數上次字符串中的數值個數,由於上次字符串有1個1, 4 * 因此輸出11;n=3時,因爲上次字符是11,有2個1,因此輸出21;n=4時,因爲上次字符串是21, 5 * 有1個2和1個1,因此輸出1211。依次類推,寫個countAndSay(n)函數返回字符串。 6 * 7 * 解題思路 8 * 第一種狀況:n<0時返回null。 9 * 第二種狀況:當n=1時,返回1 10 * 第三種狀況:當n>1時,假設n-1返回的字符串是s,對s的串進行處理,對不一樣的數字 11 * 進行分組好比112365477899,分紅11,2,3,6,5,4,77,8,99。最有就2個1, 12 * 1個2,1個3,1個6,1個5,一個4,2個7,1個8,2個9,就是211213161614271829,返回此結果。 13 */
理解題意以後,其餘的就好辦了:函數
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(); } }
固然也能夠用遞歸來作,其實道理是同樣的,速度稍微慢一點:ui
public class Solution { public String countAndSay(int n) { if(n == 1) { return "1"; } String s = countAndSay(n-1); int i = 0; String out = ""; while(i < s.length()) { int j = i+1; while(j < s.length() && s.charAt(i) == s.charAt(j)) { j += 1; } out = out + (j-i) + s.charAt(i); i = j; } return out; } }
題目的理解很是重要,有的時候靠本身的猜想是不正確的。spa