Length of Last Word
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.
int lengthOfLastWord(string s) {
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
if(s[i]==' ' && ans>0) return ans;
if(s[i]!=' ' )ans++;
}
return ans;
}
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
len++;
tail--;
}
return len;
}
Comments
Post a Comment