Home Length of Last Word
Post
Cancel

LeetCode #58: Length of Last Word (C/C++).

easy

source: https://leetcode.com/problems/length-of-last-word/
C/C++ Solution to LeetCode problem 58. Length of Last Word.

Problem


Given a string s consisting of words and spaces, return the length of the last word in the string.

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

Examples


Example 1:

Input: s = “Hello World”
Output: 5
Explanation: The last word is “World” with length 5.

Example 2:

Input: s = “   fly me   to   the moon  ”</pre>
Output: 4
Explanation: The last word is “moon” with length 4.

Example 3:

Input: s = “luffy is still joyboy”
Output: 6
Explanation: The last word is “joyboy” with length 6.

Constraints


  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Solution


This one is easy:

  • We start from the end of the string.
  • Move to prev character while there are spaces.
  • Move to prev character while there are NOT spaces and count.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
  int lengthOfLastWord(string s) {
    int i = s.size() - 1;
    int c = 0;
    while(i >= 0 && s[i] == ' ')
      i--;
    
    while(i>=0 && s[i] != ' ') {
      c++;
      i--;
    }

    return c;    
  }
};
This post is licensed under CC BY 4.0 by the author.

Insert Interval

Spiral Matrix II