> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-25-2022-58.md).

# 01/25/2022 58

First trim the tailing space of this string. Then iterate from the end, if the character is not space, decrement the index and increment the length.

Time O(N)

Space O(1)

class Solution {&#x20;

public int lengthOfLastWord(String s) {&#x20;

//remember the corner case: there maybe spaces after the last word int p = s.length() - 1;

```
    //first trim the trailing space
    while (p >= 0 && s.charAt(p) == ' ' ){
        p--;
    }
  
    int length = 0;
    while (p >= 0 && s.charAt(p) != ' '){
            p--;
            length++;
    }
    return length;
}
```

}
