Easy understand solution in C++, but with a strange question.


  • -1
    C

    Finally AC, but I still got a question. Please help me!
    I used to use

    string new Str;
    newStr="";
    

    to empty the string, but always got a wrong answer.
    Input: 1
    Output: "1"
    Expected: "1"
    I am so confused that the expected is the same as my output.

    then I find a function string::clear(), I replace all the newStr=""; with newStr.clear() and the submission accepted.

    Anyone can tell me why? I check the difference between them with this and got two yes.

    string str;
    str="assdf";
    str="";
    if (str.empty()) {
        cout<<"Yes to 1\n";
    }
    str="abcd";
    str.clear();
    if (str.empty()) {
        cout<<"Yes to 2\n";
    }
    

    Here is my AC code.(Runtime: 8 ms)

    class Solution {
    public:
        string countAndSay(int n) {
            string oldStr="1";//initial the original string
            string newStr;
            newStr.clear();//make it empty. I used to use    newStr="";  but got wrong
            for(int k=2;k<=n;k++)
            {
                int i=0;
                int count=0;//count the same number
                char ch='\0';//record the number
                char temp[20];// a temp string
                while (i<=oldStr.size()) {
                    if(ch=='\0')
                    {
                        ch=oldStr[i];
                        count++;
                    }
                    else if(oldStr[i]==ch)
                    {
                        count++;
                    }
                    else
                    {
                        sprintf(temp,"%d%c", count,ch);
                        newStr+=temp;
                        ch=oldStr[i];
                        count=1;//count a new number
                    }
                    i++;
                }
                oldStr=newStr;
                newStr.clear();
            }
            return oldStr;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.