38.Count and Say

来源:互联网 发布:淘宝双收藏是什么意思 编辑:程序博客网 时间:2024/06/15 08:00

Description:

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.

思路解析:这个题目有点诡异啊...一开始都没太搞明白到底是什么意思,后来才明白第n次的输出是固定的,由第n-1的输出所决定的。总之是感觉莫名其妙的,有点难以理解。

public class Solution {      String countAndSayForOneString(String input) {          char tmp = input.charAt(0);          int  num = 1;          StringBuffer newString = new StringBuffer("");          for(int k=1;k<input.length();k++) {              if(input.charAt(k)==tmp) {                  num++;                  continue;              }              newString.append(Integer.toString(num) + tmp);              tmp = input.charAt(k);              num = 1;          }          newString.append(Integer.toString(num) + tmp);          return newString.toString();      }            public String countAndSay(int n) {          String result = "1";          int i = 1;          while(i<n) {              result = countAndSayForOneString(result);              i++;          }          return result;      }  }