c++ simple solution


  • 0
    H
    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n = s.size(), len = 0;
            if(!n) return len;
            bool space = false; // indicate whether the previous char is ' '
            for(char c : s) {
                if(c == ' ') space = true;
                else {
                    if(space) {
                        space = false;
                        len = 1;
                    }
                    else len ++;
                }
            }
            return len;
        }
    };
    

Log in to reply
 

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