C++ O(n) easy and concise


  • 0
    A

    Loop from the back, skip the blanks, count non blank chars until encountering another blank.

        int lengthOfLastWord(string s) {
            int length = 0;
            for (int i = s.size() - 1 ; i >= 0 ; --i) {
                if (s[i] != ' ') length++;
                else if (length != 0) break;
            }
            return length;
        }
    

Log in to reply
 

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