38. Count and Say

原题题目如下截图:

自己在看这道题的时候一开始有点偏差。

题目上写着:

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.

那么这三条语句是三条生成规则,还是仅仅是字符串生成的举例呢?如果是前者,那么就是根据前一个字符串,遇到1就生成11, 遇到11 就生成21,遇到21就生成1211,遇到 2就生成 12, 那么第6个字符串就是:2111121211

后面查了一下别人对题意的理解(https://blog.csdn.net/makuiyu/article/details/43541027),

后续生成的字符串为:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
  6. 312211
  7. 13112221
  8. 1113213211
  9. 31131211131221
  10. 13211311123113112211
  11. 11131221133112132113212221
  12. 3113112221232112111312211312113211
  13. 1321132132111213122112311311222113111221131221
  14. 11131221131211131231121113112221121321132132211331222113112211
  15. 311311222113111231131112132112311321322112111312211312111322212311322113212221

那么,也就是说题目中的那三句话仅仅是举个例子而已。

解题思路为: 首先预设第一个字符串s为“1”,如果输入参数为1,直接返回预设的字符串,否则以循环的方式一步一步生成新的字符串。

新字符串的生成方式为:

1、从左到右遍历上一个字符串,以循环的方式计算当前位置字符在其右边连续出现的次数,并以   出现次数 + 当前字符   的形式添加到一个临时的字符串右边;

2、然后从新的不同的字符继续前面的步骤,直到完成上一个字符串的遍历。

贴上代码:

 1 class Solution {
 2     public String countAndSay(int n) {
 3         String s = "1";
 4         
 5         if(n == 1){
 6             return s;
 7         }
 8         
 9         for( int i = 1 ; i < n ; i++){
10             String temp = "";
11             for( int j = 0 , count = 0; j < s.length() ; j = j + count){
12                 count = 0;
13                 for( int index = j ; index < s.length() ; index++){
14                     if( s.charAt(j) == s.charAt(index) ){
15                         count++;
16                     }else{
17                         break;
18                     }
19                 }
20                 temp += Integer.toString(count) + s.charAt(j);
21             }
22             s = temp;
23         }
24         return s;
25     }
26 }

END

原文地址:https://www.cnblogs.com/sssysukww/p/8707598.html