标签:
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.
String
#include <string> #include <iostream> #include <sstream> using namespace std; class Solution { public: string countAndSay(int n) { if(n<=0) return "0"; if(n==1) return "1"; string curStr="1",retStr=""; for(int i=1;i<n;i++){ int cnt = 1; retStr=""; for(int j=1;j<curStr.size();j++){ if(curStr[j-1]==curStr[j]) cnt++; else{ stringstream ss; ss<<cnt<<curStr[j-1]; retStr+=ss.str(); cnt=1; } } stringstream ss; ss<<cnt<<curStr[curStr.size()-1]; retStr+=ss.str(); curStr=retStr; } return retStr; } }; int main() { Solution sol; for(int i=0;i<10;i++){ string ret=sol.countAndSay(i); cout<<"i:"<<ret<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4211599.html