Skip to content

Commit d85c129

Browse files
committed
Implement LengthOfLastWord algorithm in strings package
1 parent 0837424 commit d85c129

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* The {@code LengthOfLastWord} class provides a utility method to determine
5+
* the length of the last word in a given string.
6+
*
7+
* <p>A "word" is defined as a maximal substring consisting of non-space
8+
* characters only. Trailing spaces at the end of the string are ignored.
9+
*
10+
* <p><strong>Example:</strong>
11+
* <pre>{@code
12+
* LengthOfLastWord obj = new LengthOfLastWord();
13+
* System.out.println(obj.lengthOfLastWord("Hello World")); // Output: 5
14+
* System.out.println(obj.lengthOfLastWord(" fly me to the moon ")); // Output: 4
15+
* System.out.println(obj.lengthOfLastWord("luffy is still joyboy")); // Output: 6
16+
* }</pre>
17+
*
18+
* <p>This implementation runs in O(n) time complexity, where n is the length
19+
* of the input string, and uses O(1) additional space.
20+
*/
21+
public class LengthOfLastWord {
22+
23+
/**
24+
* Returns the length of the last word in the specified string.
25+
*
26+
* <p>The method iterates from the end of the string, skipping trailing
27+
* spaces first, and then counts the number of consecutive non-space characters
28+
* characters until another space (or the beginning of the string) is reached.
29+
*
30+
* @param s the input string to analyze
31+
* @return the length of the last word in {@code s}; returns 0 if there is no word
32+
* @throws NullPointerException if {@code s} is {@code null}
33+
*/
34+
public int lengthOfLastWord(String s) {
35+
int sizeOfString = s.length() - 1;
36+
int lastWordLength = 0;
37+
38+
// Skip trailing spaces from the end of the string
39+
while (sizeOfString >= 0 && s.charAt(sizeOfString) == ' ') {
40+
sizeOfString--;
41+
}
42+
43+
// Count the characters of the last word
44+
while (sizeOfString >= 0 && s.charAt(sizeOfString) != ' ') {
45+
lastWordLength++;
46+
sizeOfString--;
47+
}
48+
49+
return lastWordLength;
50+
}
51+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package com.thealgorithms.strings;
2+
3+
public class LengthOfLastWordTest {
4+
}

0 commit comments

Comments
 (0)