C++ Simple Solution For Beginners, RunTime: 3ms, Worst Case:O(n), Avg Case: 0(last_word_length)


  • 0

    Very simple solution for beginners.

    Solution2 uses an index based for loop and Solution1 uses reverse iterators.
    Idea: Start counting each non-white space char starting from the very back of the string moving toward the front of the string until you encounter a white space char. Once you encounter a white space char ' ', return the count. Purpose of flag f is to skip any white space chars ' ' that may be at the very end of the string.

    Solution 1:

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int cnt=0,f=0;
            for(auto i=s.rbegin(); i!=s.rend(); i++){
                if(*i!=' '){cnt++; f=1;}  //dereference iterator with *i 
                else if(f==1) break;
            }
            return cnt;
        }
    };
    

    Solution 2:

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int cnt=0,f=0;
            for(int i=s.size()-1; i>=0; i--){
                if(s[i]!=' '){cnt++; f=1;}
                else if(f==1) break;
            }
            return cnt;
        }
    };
    

Log in to reply
 

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