(leetcode) countandsay

时间:2023-03-08 17:20:45
class Solution {
public:
string calcuate(string s)
{
string result;
char pre = s[0];
int cnt = 1;
for(int i =1;i < s.length();i++)
{
if(s[i] == pre)
{
cnt++;
}
else
{
char tmp = cnt+'0';
result += tmp + pre;
pre = s[i];
cnt=1;
} }
char tmp = cnt + '0';
result += tmp + pre; return result;
}
string countAndSay(int n) {
string ret;
ret = "1";
int j = 1;
while(j < n)
{
ret = calcuate(ret);
j++;
}
return ret;
}
};

  上面方法错误 原因是由于使用 result += tmp +pre;这个操作

下面是修改后的代码:
class Solution {
public:
string calcuate(string s)
{
string result;
char pre = s[0];
int cnt = 1;
for(int i =1;i < s.length();i++)
{
if(s[i] == pre)
{
cnt++;
}
else
{
char tmp = cnt+'0';
result = result + tmp + pre;
pre = s[i];
cnt=1;
} }
char tmp = cnt + '0';
result = result+ tmp + pre; return result;
}
string countAndSay(int n) {
string ret;
ret = "1";
int j = 1;
while(j < n)
{
ret = calcuate(ret);
j++;
}
return ret;
}
};