您的位置:首页 > 其它

[leetcode]50 Count and Say

2015-04-07 16:03 369 查看
题目链接:https://leetcode.com/problems/count-and-say/

Runtimes:12ms

1、问题

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.

2、分析

数并且说出来,题目简单,请看英文实例~

3、小结

严谨的思路~

4、实现

class Solution {
public:
string change(int n)
{
string s = "";
if (n >= 0 && n <= 9)
return s += (n + '0');
while (n > 0)
{
s += (n % 10) + '0';
n /= 10;
}
int i = 0, j = s.length() - 1;
while (i < j)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
}
return s;
}

string countAndSay(int n) {
if (n <= 0)
return "";
int i = 1;
string result = "1";
while (i < n)
{
string tmp = "";
int j = 1, start = 0;
for (; j < result.length(); ++j)
{
if (result[j] != result[start]){
tmp = tmp + change(j - start) + result[start];
start = j;
}
}
tmp += change(j - start) + result[start];
result = tmp;
//cout << result << endl;
++i;
}
return result;
}
};


5、反思

好像可以跑得更快的!待改进~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: