🎨 Try our Free AI Image Generation Feature

58. Length of Last Word

avatar
Dare2Solve

1 year ago

58. Length of Last Word

Intuition

To find the length of the last word in a string:

  • Traverse the string from the end to skip any trailing spaces.
  • Count characters of the last word until a space is encountered or the beginning of the string.

Approach

  1. Initialization: - Start with length set to 0. - Use a pointer i starting from the end of the string.
  2. Skip Trailing Spaces: - Move the pointer i backwards until a non-space character or the beginning of the string is encountered.
  3. Count Characters: - While i is greater than or equal to 0 and s[i] is not a space: - Increment length and move i backwards.
  4. Return Result: - After counting the characters of the last word, return length.

Complexity

Time Complexity:

O(n), where n is the length of the string s. This is because we iterate through the string once.

Space Complexity:

O(1), as we use only a constant amount of extra space.

This approach efficiently computes the length of the last word in a string, handling spaces and ensuring correctness based on the problem's requirements.

Code

C++

#include 
using namespace std;

class Solution {
public:
    int lengthOfLastWord(string s) {
        int length = 0;
        int i = s.length() - 1;

        // Skip trailing spaces
        while (i >= 0 && s[i] == ' ') {
            i--;
        }

        // Count the length of the last word
        while (i >= 0 && s[i] != ' ') {
            length++;
            i--;
        }
        return length;
    }
};

Python

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        length = 0
        i = len(s) - 1
        
        # Skip trailing spaces
        while i >= 0 and s[i] == ' ':
            i -= 1
        
        # Count the length of the last word
        while i >= 0 and s[i] != ' ':
            length += 1
            i -= 1
        
        return length

Java

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        int i = s.length() - 1;

        // Skip trailing spaces
        while (i >= 0 && s.charAt(i) == ' ') {
            i--;
        }

        // Count the length of the last word
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;
            i--;
        }

        return length;
    }
}

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function (s) {
    let res = 0;
    for (let i = s.length - 1; i >= 0; i--) {
        if (s[i] != ' ') res++;
        else {
            if (res > 0) return res;
        }
    }
    return res;
};