Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions String/Count And Say
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
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.

Example:

if n = 2,
the sequence is 11.
*/


string Solution::countAndSay(int n) {
if (n == 1) return "1";
if (n == 2) return "11";
string str = "11";
for (int i = 3; i<=n; i++)
{
str += '$';
int len = str.length();

int cnt = 1;
string tmp = "";

for (int j = 1; j < len; j++)
{

if (str[j] != str[j-1])
{
tmp += cnt + '0';
tmp += str[j-1];
cnt = 1;
}
else cnt++;
}
str = tmp;
}
return str;
}