|
| 1 | +packagecom.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 | +publicclassLengthOfLastWord { |
| 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 | +publicintlengthOfLastWord(Strings) { |
| 35 | +intsizeOfString =s.length() -1; |
| 36 | +intlastWordLength =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 | +returnlastWordLength; |
| 50 | + } |
| 51 | +} |