0ms Java, 1 for loop


  • 0
    public int lengthOfLastWord(String s) {
        int len = 0;
        boolean flag = false;
        for (int i=s.length()-1; i>=0; i--) {
            if (s.charAt(i)!=' ') {
                flag = true;
                len++;
            }
            if (flag && s.charAt(i)==' ') break;
        }
        return len;
    }

Log in to reply
 

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