58. Length of Last Word

Input: s = "Hello World"
Output: 5
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;
}
};
  1. “a “ -> 1 : to solve this corner case, I use variable prev to store the previous value of len.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store