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.
Note: The sequence of integers will be represented as a string.
解题思路:
这道题的题意就是按某种顺序产生某一位的字符串,其规则是:
若n=1,那么为s[n]="1"
若n>0,那么逐个读取s[n-1]中相同的字符,然后说k个这个字符,直到s[n-1]读玩为止。比如111221可以这么读,3个1,2个2,1个1,于是下一个字串为312211。
显然用递归最合适。
class Solution { public: string countAndSay(int n) { if(n==1){ return "1"; } string s=countAndSay(n-1); int len=s.length(); string result=""; char lastChar=s[0]; int count=1; char charNum; for(int i=1; i<len; i++){ if(s[i]==lastChar){ count++; continue; } charNum = count + '0'; result = result + charNum + lastChar; lastChar=s[i]; count=1; } charNum = count + '0'; result = result + charNum + lastChar; //注意这里有个陷阱,在循环外需要这么加 return result; } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45461567