这一道题目,很相似于小学的问题,可是若是硬是要将输入和结果产生数值上的联系就会产生混乱了,所以咱们要打破思惟定势。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