The website replies "runtime error", last string is "a".


  • 1
    U

    I have tested my code on my computer. And all the result are correct. I don't know why what is the problem with entering "a" into that.

        void solution::strRev(string &s)
    
    {
    int wordLen = 0, len, start = s.length();
    
    string temp;
    
    if (s.length() != 0)
    {
    	while (s.at(0) == ' ') s.erase(0, 1); // Delete the spaces ahead.
    
    	len = s.length();
    
    	while (s.at(len - 1) == ' ') // Delete the space consecutivly.
    	{
    		s.erase(len - 1, 1);
    
    		len = s.length();
    	}
    
    
    	for (int i = len - 1; i >= 0; i--)
    	{
    		wordLen += 1;
    
    		if (i <= len - 1)
    		{
    			if ((s.at(i) == ' ') && (s.at(i + 1) != ' '))
    			{
    				start = i;
    
    				temp.append(s, start + 1, wordLen - 1);
    				temp.append(" ");
    
    				wordLen = 0;
    			}
    			else if ((s.at(i) == ' ') && (s.at(i + 1) == ' '))
    			{
    				s.erase(i, 1);
    
    				len = s.length();
    
    				wordLen = 0;
    			}
    			else if (i == 0)
    			{
    				start = i;
    
    				temp.append(s, start, wordLen);
    
    				wordLen = 0;
    			}
    		}
    	}
    
    	s.assign(temp);
    }
    else
    {
    	printf("\nThere is not any words in this sentencs. \n");
    }
    

    }


  • 0
    S

    Your code has multiple problems, including but not limited to:

    while (s.at(0) == ' ') s.erase(0, 1); // Delete the spaces ahead.
    
    len = s.length();
    
    while (s.at(len - 1) == ' ') ...
    

    So what would happen if s contains only spaces? You will end up vising s.at(-1)

    else
    {
        printf("\nThere is not any words in this sentencs. \n");
    }
    

    No output statement please.

    By the way, erasing from a string is an O(n) operation, so you should try to refrain from using it as much as possible, let alone using it in a loop.


Log in to reply
 

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