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 = "Hello World"
,
return 5
.
找最后的单词的长度,这里申明两个变量,一个记录当前访问的单词的长度curLen,一个记录前一个访问的单词的长度lastLen(如果当前访问的单词长度访问完成,并且长度不为0,则更新当前长度为lastLen=curLen)。当字符串遍历完后,如果curLen不为0,表示最后单词后无空格,curLen为最后单词的长度,如果curLen为0,表示最后单词的后面有空格,lastLen为最后单词的长度。
class Solution { public: int lengthOfLastWord(const char *s) { if(s==NULL||*s=='\0')return 0; int curLen=0,lastLen=0; while(*s!='\0'){ if(*s==' '){ if(curLen>0)lastLen=curLen; curLen=0; }else curLen++; s++; } if(curLen>0)return curLen; else return lastLen; } };