[LeetCode] Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, …

1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, thenone 1"or1211.

Given an integern, generate thenthsequence.

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;}};

获得幸福的二法门是珍惜你所拥有的、遗忘你所没有的

[LeetCode] Count and Say

相关文章:

你感兴趣的文章:

标签云: