您的位置:首页 > 其它

LeetCode-Count and Say

2013-08-03 20:55 225 查看
class Solution {
public:
string countAndSay(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string str = "1";
string strN = "";
char buf[100];
for (int i = 0; i < n - 1; ++i)
{
int cnt = 1;
int j;
for (j = 1; j < str.size(); ++j)
{
if (str[j] == str[j - 1])
{
++cnt;
}
else
{
//这里要特别注意不能直接strN += cnt + '0',因为strN有可能不是一位数
itoa(cnt, buf);
strN += buf;
strN += str[j - 1];
cnt = 1;
}
}
itoa(cnt, buf);
strN += buf;
strN += str[j - 1];
str = strN;
strN = "";
}
return str;
}

void itoa(int i, char *a)
{
int j = 0;
while (i != 0)
{
int tmp = i % 10;
a[j++] = tmp + '0';
i /= 10;
}
a[j] = '\0';
reverse(a, a + j);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: