My simple cpp code


  • 0
    C
    class Solution {
    public:
        int lengthOfLastWord(string s) 
        {
            int lenOfLastWord = 0;
            int idx = s.size()-1;
            
            // skip whitespaces
            while(idx >= 0 && s[idx] == ' ')
                idx--;
                
            while(idx >= 0 && s[idx] != ' ')
            {
                idx--;
                lenOfLastWord++;
            }
            
            return lenOfLastWord;
        }
    };

Log in to reply
 

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