首页 > 代码库 > 【Problem】Count and Say

【Problem】Count and Say

问题分析

  题目理解:给定一个整数,如果相邻的几个数位数字是相同的,则输出重复出现的次数加上该数字本身;继续向后查找直到所有的数位处理完。

  按照上述思路,则:

input

output

1

11

11

21

21

1211

  但实际运行时提示出错,在输入为1的时候输出结果为11,而实际的应该是1。接着发现题目意思理解错了,如下图所示,后面的输出结果是依赖与前面的输出结果的。比如第一个输出为1;第二个输出是对1进行上述运算,即11;同理,第三个是对11进行运算,即21;接着依次是1211、111221、312211、13112221、1113213211……

源代码

 1 public class Solution { 2     public String countAndSay(int n) { 3          4         if ( n == 1 ) { 5             return "1"; 6         } else { 7              8             char current;    // the current char 9             int count;       // the count of the current char10             String result = new String("1");  // the result11             int length = result.length();     // the length of the result string12             StringBuilder strBuilder = new StringBuilder(); // store the current result13             14             int i = 0;15             while ( n > 1 ) {16                 for ( i = 0; i < length; i++ ) {17                     current = result.charAt(i);18                     count = 1;19                     // while the next char is the same as the current char20                     while ( (i+1 < length) &&21                             (result.charAt(i+1) ==  current) ) {22                         count++;23                         i++;24                     }25                     // add the char and its count to the current result26                     strBuilder.append(count).append(current);27                 }28                 // update the result and its length, and clear the content of strBuilder for the next loop29                 result = strBuilder.toString();30                 length = result.length();31                 strBuilder = new StringBuilder();32                 n--;33             }34 35             return result;36         }37     }38 }

【Problem】Count and Say