Saturday, September 5, 2020

[LeetCode] 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 (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Example:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.


Approach: This is a simple implementation problem. You can just look at the implementation to understand the approach.


Implementation in C#:

    public int LengthOfLastWord(string s)
    {
        int length = s?.Length ?? 0;
        if (length == 0)
        {
            return 0;
        }
        int endIndex = length - 1;
        while (endIndex >= 0 && s[endIndex] == ' ')
        {
            --endIndex;
        }
        if (endIndex < 0)
        {
            return 0;
        }
        int startIndex = endIndex - 1;
        while (startIndex >= 0 && s[startIndex] != ' ')
        {
            --startIndex;
        }
        return endIndex - startIndex;
    }

Complexity: O(n)

No comments:

Post a Comment