MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / lengthOfLastWord

Method lengthOfLastWord

58-length-of-last-word/Solution.java:2–18  ·  view source on GitHub ↗
(String s)

Source from the content-addressed store, hash-verified

1public class Solution {
2 public int lengthOfLastWord(String s) {
3 int n = s.length() - 1;
4 int length = 0;
5
6 // Step 1-> skip trailing spaces
7 while (n >= 0 && s.charAt(n) == ' ') {
8 n--;
9 }
10
11 // Step 2-> count last word length
12 while (n >= 0 && s.charAt(n) != ' ') {
13 length++;
14 n--;
15 }
16
17 return length;
18 }
19}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected