What is wrong with the following code?


  • 0
    Q
    class Solution {
    public:
    int lengthOfLastWord(string s) 
    {
        if(s=="")
            return 0;
        if(s==" ")
            return 0;
        size_t pos = s.find_last_of(" ");
        
        if(pos != string::npos)
        {
            string sub = s.substr(pos);
            return sub.length();
        }
        else
            return s.length();
    }
    };

  • 0
    J

    so many bad cases, for example, if the string like "abc ", there are one space at last position, the answer of your algorithm is wrong.

    My C++ solution:

    1. Firstly, remove all spaces at tail
    2. From the last non-space to start, calculate the length and end the algorithm if the character is space

    ================================================

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            if(s == "")
                return 0;
            int index = s.length() - 1;
            for(int i = s.length() - 1; i >= 0; i--)
                if(s[i] != ' '){
                    index = i;
                    break;
                }
            int ret = 0;
            for(int i = index; i >= 0; i--){
                if(s[i] == ' ')
                    break;
                ret++;
            }
            return ret;
        }
    };

Log in to reply
 

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