C++ 4ms solution


  • 0
    C
    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int len=0;
            int pos;
            
            while (s.length()!=0){
                pos = s.find(" ");
                if (pos==string::npos)
                    return s.length();
                else{
                    if (pos!=0)
                        len = pos;
                    s.erase(0,pos+1);
                }
            }
            return len;
        }
    };

  • 0
    L

    My easy understand solution.

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int count = s.size();
            if(count == 0) return 0;
            int cur = count - 1;
    
            // find the last space
            while(cur >= 0 && s[cur] != ' ') cur--;
            if(cur != count - 1) return count - 1 - cur;
            
            // skip continuous spaces
            while(cur >= 0 && s[cur] == ' ') cur--;
            
            // find the previous space of last word
            int len = 0;
            while(cur >= 0 && s[cur] != ' ') cur--, len++;
            return len;
        }
    };

Log in to reply
 

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