Length Of Last Word Problem


Description

LeetCode Problem 58.

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

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

Example 1:

1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

1
2
3
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ‘ ‘.
  • There will be at least one word in s.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
    /* Start from the tail of s and move backwards to find the first non-space character. 
    Then from this character, move backwards and count the number of non-space characters 
    until we pass over the head of s or meet a space character. The count will then be the 
    length of the last word. */
    int lengthOfLastWord(string s) { 
        int len = 0, tail = s.length() - 1;
        while (tail >= 0 && s[tail] == ' ') tail--;
        while (tail >= 0 && s[tail] != ' ') {
            len++;
            tail--;
        }
        return len;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...