Java solution (4 ms, beats 99.46%)


  • 0
    A
     public int lengthOfLastWord(String s) {
            int i = s.length() - 1;
            boolean foundWord = false;
            int suffix = 0;
            for (; i >= 0; i--) {
                if (s.charAt(i) != ' ') {
                    foundWord = true;
                } else if (foundWord) {
                    break;
                } else {
                    suffix++;
                }
            }
            return foundWord ? s.length() - i - 1 - suffix : 0;
        }
    

Log in to reply
 

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