Skip to content

Latest commit

 

History

History
56 lines (43 loc) · 1.08 KB

File metadata and controls

56 lines (43 loc) · 1.08 KB

58. Length of Last Word

Description

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ' '.

Solution

  • java
/*
 Success Detail:
 Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
 Memory Usage: 36.4 MB, less than 98.02% of Java online submissions for Length of Last Word.
 */
class Solution {
    public int lengthOfLastWord(String s) {
        int right = s.length() - 1;
        while (right >= 0 && s.charAt(right) == ' ') {
            right--;
        }
        if (right < 0) {
            return 0;
        }
        int left = right;
        while (left >= 0 && s.charAt(left) != ' ') {
            left--;
        }
        return right - left;
    }
}