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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string str = "1";
if (n == 1)
return str;
for (int i = 1; i < n; i++)
{
string new_str = "";
int count = 0;
char ch, pre = '0';
bool flag = false;
for (int k = 0; k < str.length(); k++)
{
ch = str[k];
if (ch == pre || k == 0)
{
count++;
}
if ( (k > 0 && ch != pre ) || k == str.length()-1)
{
flag = true;
}
if (flag)
{
// update new_str
char tmp = '0' + count;
new_str += tmp;
if (k > 0)
new_str += pre;
else
new_str += ch;
count = 1;
flag = false;
}
// check the last character
if ( k > 0 && k == str.length()-1 && ch != pre)
{
// we know we have to process the
new_str += '1';
new_str += ch;
}
pre = ch;
}
// update str
str = new_str;
}
return str;
}
};
No comments:
Post a Comment