58. Length of Last Word

Andreea
1 min readMay 6, 2021

--

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

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

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0
class Solution {
public:
int lengthOfLastWord(string s) {

//String last = "";

if(s == " "){
return 0;
}

int len = 0;
int prev = 0;

for(int i=0; i<s.length(); i++){
if(s[i] == ' '){
len = 0;
continue;
}
else{
len++;
}

if(len != 0){
prev = len;
}
}

return (len==0)? prev:len;
}
};

TIPS:

corner case:

  1. “ “ -> 0
  2. “a “ -> 1 : to solve this corner case, I use variable prev to store the previous value of len.

Runtime: 4 ms, faster than 64.17% of C++ online submissions for Length of Last Word.

Memory Usage: 6.5 MB, less than 59.45% of C++ online submissions for Length of Last Word.

--

--

Andreea