[LeetCode] 58. Length of Last Word

Problem

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

1
2
Input: "Hello World"
Output: 5

Explanation

  1. We can solve it in one line. First trim the string and get its length len, then subtract 1 is the last index, then again subtract the last index of space of the trimmed string, which returns us the last word’s length.

  2. The second way is create a pointer that starts from the end, find the last character’s index, then set the result counter to 0. Increase 1 until the pointer poinits to empty space. Return the counter result.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public int lengthOfLastWord(String s) {
        // return s.trim().length() - 1 - s.trim().lastIndexOf(" ");

        if (s.length() == 0) return 0;
        int right = s.length()-1;
        while (right >= 0 && s.charAt(right) == ' ') {
            right -= 1;
        }
        int res = 0;
        while (right >= 0 && s.charAt(right) != ' ') {
            right -= 1;
            res += 1;
        }

        return res;
    }
}