Simplest way to solve this problem in c++


#1

string Solution::countAndSay(int A) {
if(A==1)
return “1”;
if(A==2)
return “11”;
string s=“11”;

for(int i=3;i<=A;i++)
{
    s+='&';
    int n=s.length();
    int count=1;
    string temp="";
    for(int j=1;j<n;j++)
    {
        if(s[j]!=s[j-1])
        {
            temp+=count+'0';
            temp+=s[j-1];
            count=1;
        }
        else
            count++;
    }
    s=temp;
}
return s;

}


#2

@btbti18026upasana_90 Can you please tell me why have you used
s+=’&’; ?


#3

To prevent the condition for string length overflow. Just to make sure we never run outside the string.


#4

What is the purpose of adding ‘0’ with count to temp?


#5

See, count is an integer so to convert it we add ‘0’
The relation is ‘count’ - ‘0’ = count
Example: ‘1’ - ‘0’ = 1 where ‘1’ is a character and 1 is an integer


#6

Don’t you think you should add the below lines for the last element in the string after the for loop ends.

for(int j=1;j<n;j++)
{
    if(s[j]!=s[j-1])
    {
        temp+=count+'0';
        temp+=s[j-1];
        count=1;
    }
    else
        count++;
}
temp+=count+'0';
temp+=s[j-1];
s=temp;