Easy Java 0ms Solution


  • 0
    public int lengthOfLastWord(String s) {
        boolean seenWord = false;
        int wordCount = 0;
        for(int i=s.length()-1; i>=0; i--) {
            if(s.charAt(i)==' ' && !seenWord) {
                // ignore any trailing spaces
            } else if(!seenWord) { // first time seen non-space character
                seenWord = true;
                wordCount++;
            } else if (s.charAt(i)==' ') { // seenWord but found space
                return wordCount;
            } else {
                wordCount++;
            }
        }
        return wordCount;
    }

Log in to reply
 

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