This problem is about finding the length of the last word in a given string. A word is defined as a maximal substring consisting of non-space characters only.
Steps
- Start from the end of the string and skip any trailing spaces.
- Once a non-space character is found, start counting until a space is encountered again.
- The counted length is the length of the last word.
Dry Run
Input: "Hello World "
- Skip trailing spaces → pointer now at index 10 (character ‘d’)
- Start counting: ‘d’, ‘l’, ‘r’, ‘o’, ‘W’ → total count = 5
- Encounter space → stop
Output: 5
Edge Case
Input: " " → Only spaces
Output: 0
Time & Space Complexity
- Time Complexity: O(n), where n is the length of the string
- Space Complexity: O(1) — no extra space used
var lengthOfLastWord = function (s) {
let n = s.length - 1
while (n>=0) {
if (s[n] === ' ') {
--n;
} else {
break;
}
}
let count = 0
while (n >= 0) {
if (s[n] != " ") {
--n;
++count;
}
else {
break
}
}
return count;
};
#include <string>
using namespace std;
int lengthOfLastWord(string s) {
int n = s.length() - 1;
while (n >= 0 && s[n] == ' ') {
--n;
}
int count = 0;
while (n >= 0 && s[n] != ' ') {
--n;
++count;
}
return count;
}
#include <stdio.h>
int lengthOfLastWord(char * s){
int n = strlen(s) - 1;
while (n >= 0 && s[n] == ' ') {
--n;
}
int count = 0;
while (n >= 0 && s[n] != ' ') {
--n;
++count;
}
return count;
}
import java.util.HashMap;
public class Solution {
public int lengthOfLastWord(String s) {
int n = s.length() - 1;
while (n >= 0 && s.charAt(n) == ' ') {
--n;
}
int count = 0;
while (n >= 0 && s.charAt(n) != ' ') {
--n;
++count;
}
return count;
}
}
class Solution:
def lengthOfLastWord(self, s: str) -> int:
n = len(s) - 1
while n >= 0 and s[n] == ' ':
n -= 1
count = 0
while n >= 0 and s[n] != ' ':
n -= 1
count += 1
return count
