Length of Last Word
LeetCode 58 | Difficulty: Easyβ
EasyProblem Descriptionβ
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.
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 "
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 <= 10^4`
- `s` consists of only English letters and spaces `' '`.
- There will be at least one word in `s`.
Topics: String
Approachβ
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
When to use
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 132 ms)β
| Metric | Value |
|---|---|
| Runtime | 132 ms |
| Memory | N/A |
| Date | 2017-10-22 |
Solution
public class Solution {
public int LengthOfLastWord(string s) {
if(string.IsNullOrEmpty(s) || s.Split(new char[] { ' '},StringSplitOptions.RemoveEmptyEntries).Count()==0)
return 0;
var result = s.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries).ToArray();
return result[result.Length-1].Length;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.