Leetcode字符串专题
Leetcode38. Count and Say
分析:根据题意,数列的下一项就是统计上一项中每个数字出现的次数,理解清楚题意就很简单了
1 class Solution { 2 public: 3 string solve(string s){ 4 string p=""; 5 int len=s.length(); 6 int count=1; 7 for(int i=1;i<=len;i++){ 8 if(s[i]==s[i-1]){ 9 count++; 10 }else{ 11 p+=count+'0'; 12 p+=s[i-1]; 13 count=1; 14 } 15 } 16 return p; 17 } 18 public: 19 string countAndSay(int n) { 20 string res="1"; 21 for(int i=2;i<=n;i++) 22 res=solve(res); 23 return res; 24 } 25 };