leetcode:Count and Say
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时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推(不断数数),写个countAndSay(n)函数返回字符串。
class Solution { public: string convert(const string &say) { stringstream ss; //创建一个流 int count=0; char last=say[0]; for(size_t i=0; i<=say.size(); ++i) { if(last==say[i]) //每次与前一个字符比较是否相等,相等则计数加一 { ++count; } else { ss<<count<<last; //将count的值传递到流ss中,再将last的值传入 count=1; last=say[i]; } } return ss.str(); //返回流中的字符串 } string countAndSay(int n) { if(n<=0) return string(); string say="1"; //定义初始字符串的内容 for (int i=1; i<n; ++i) { say=convert(say); } return say; } };
或:
class Solution { public: string nextRead(string s) { stringstream ss; int count, i = 0, n = s.length(); while (i < n) { count = 0; while (i + 1 < n && s[i] == s[i + 1]) { i++; count++; } ss << count + 1 << s[i]; i++; } return ss.str(); } string countAndSay(int n) { string res = ""; if (n == 0) return res; res = "1"; if (n == 1) return "1"; while (n > 1) { res = nextRead(res); n--; } return res; } };
其他解法:
class Solution { public: string countAndSay(int n) { if (n==0){ return NULL; } if (n==1){ return "1"; } int count=1; string s1="1"; string s2; int j=1; if (n>=2){ s1="11"; j=2; } int i=0; while (j<n && n>1){ s2=""; for (i=0;i<s1.size();i++){ for (int m=i;m<s1.size()-1;m++){ if (s1[m]==s1[m+1]){ count++; i++; } if (s1[m]!=s1[m+1]){ break; } } s2+=to_string(count)+s1[i]; count=1; } s1=s2; j++; } return s1; } };
class Solution { public: string countAndSay(int n) { if(n==0) return " "; if(n==1) return "1"; string str="1"; string tmp; for(int i=1;i<n;++i) { tmp.clear(); int cnt=1; for(int j=0;j<str.size();++j) { while(j+1<str.size()) { if(str[j]==str[j+1]) { ++cnt; ++j; } else break; } tmp.push_back(cnt+'0'); tmp.push_back(str[j]); cnt=1; } str=tmp; } return str; } };
朱颜辞镜花辞树,敏捷开发靠得住!