地址:http://oj.leetcode.com/problems/count-and-say/
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.
思路:模拟题。参考代码:
class Solution {
public:
string countAndSay(int n) {
string str;
if(!n)
return str;
str = "1";
int len, cnt;
char ch;
queue<string>q;
for(int i = 1; i<n; ++i)
{
len = str.length();
cnt = 0;
ch = str[0];
for(int j = 0; j<len; ++j)
{
if(str[j]==ch)
++cnt;
else
{
string tmp;
tmp += char(cnt+'0');
tmp += ch;
q.push(tmp);
cnt = 1;
ch = str[j];
}
}
string tmp;
tmp += char(cnt+'0');
tmp += ch;
q.push(tmp);
tmp.clear();
while(!q.empty())
{
tmp+=q.front();
q.pop();
}
str = tmp;
}
return str;
}
};
参考代码二,记录字符和该字符个数,不要忘记最后一次的记录
class Solution {
public:
string countAndSay(int n) {
string newStr, str = "1";
char ch;
int cnt;
for(int i = 1; i<n; ++i) {
newStr = "";
ch = str[0];
cnt = 1;
for(int j = 1; j<str.length(); ++j) {
if(str[j]==ch)
++cnt;
else {
newStr += (cnt+'0');
newStr += ch;
ch = str[j];
cnt = 1;
}
}
newStr += (cnt+'0');
newStr += ch;
str = newStr;
}
return str;
}
};
Python
class Solution:
# @return a string
def countAndSay(self, n):
s = "1"
for i in range(1, n):
ch = s[0]
cnt = 1
news = ""
for j in range(1, len(s)):
if ch == s[j] :
cnt += 1
else :
news += (str(cnt) + ch)
ch = s[j]
cnt = 1
news += (str(cnt) + ch)
s = news
return s