38. Count and Say(第十二周)

来源:互联网 发布:萨尔 知乎 编辑:程序博客网 时间:2024/06/05 05:21

代码(包括测试代码):

#include <sstream>

#include <iostream>
#include <cstdlib>
using namespace std;
class Solution
{
public:
    string countAndSay(int n) 
{
string result = "1";
if(n == 1) return result;
else if(n > 1)
{
for(int i=2;i<=n;i++)
{
result = Count(result);
}
return result;
}
    }
string Count(const string &str)
   {
 stringstream ss;
 int len = str.size();
 int count = 1;
 string temp;
 string ret;
 if(len == 1) return "11";
 for(int pos = 1;pos < len;pos++)
 {
 if(str[pos] == str[pos-1])
 {
 count+=1;
 if(pos == len-1)
 {
 ss<<count;
 ss>>temp;
 ret += temp;
 ret += str[pos];
 ss.clear();
 }
 }
 else if(str[pos] != str[pos-1])
 {
 ss<<count;
 ss>>temp;
 ret += temp;
 ret += str[pos-1];
 ss.clear();
 count = 1;
  if(pos == len-1)
 {
 ss<<count;
 ss>>temp;
 ret += temp;
 ret += str[pos];
 ss.clear();
 }
 }
 }
 return ret;
    }
};
int main()
{
Solution a;
cout<<a.countAndSay(10)<<endl;
system("pause");
return 0;

}

分析:

result = Count(result);这段代码是主要的一步

还有就是每一步stream转换之后都要有clear操作,否则值是传不进去的。

这道题主要是题意不太好懂,看懂题意就好做了。

原创粉丝点击