Given a string s consists of upper/lower-case alphabets and empty space characters
' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s =
return
Given s =
"Hello World"
,return
5
.
Straightforward solution, just take care of continuous training empty signs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int lengthOfLastWord(string s) { | |
int count=0; | |
int emptyMet=1; | |
for(int i=0; i<s.length(); ++i){ | |
char c=s[i]; | |
if(c==' '){ | |
emptyMet=1; | |
continue; | |
} | |
if(c!=' '&&emptyMet==1){ | |
count=1; | |
emptyMet=0; | |
continue; | |
} | |
if(c!=' '&&emptyMet==0) | |
count++; | |
} | |
return count; | |
} | |
}; |
Round 2 Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int lengthOfLastWord(string s) { | |
int len=0; | |
for(int i=0; i<s.length(); i++){ | |
if(i-1>=0 && s[i-1]==' ' && s[i]!=' ') | |
len=0; | |
if(s[i]!=' ') | |
len++; | |
} | |
return len; | |
} | |
}; |
No comments:
Post a Comment