Simple Java solution & easy to understand beat all complicate solutions

  • 0
    public int lengthOfLastWord(String s) {
        s = s.trim();
        int res = 0;
        for(int i = s.length()-1; i>=0; i--){
            if(s.charAt(i) != ' '){
        return res;

    step 1, trim the start and end ' '
    step2, from end to start, find the first ' ' via a loop
    step3, once you find the first ' ', stop the loop and print the length and the length will be the length of the last word.

    have a nice day

Log in to reply

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