【LeetCode】58. Length of Last Word
Length of Last Word
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
.
用ret记录上一个单词的长度,用cur记录当前单词的长度。
每遇到空白符,将cur赋给ret,然后cur置零。
如果以字母结尾,返回cur
如果以空格结尾,返回ret(此时cur为0)
class Solution { public: int lengthOfLastWord(const char *s) { int ret = 0; int cur = 0; while(*s != 0) { while(*s != 0 && *s == ' ') s ++; if(*s == 0) return ret; while(*s != 0 && *s != ' ') { cur ++; s ++; } if(*s == 0) return cur; else { ret = cur; cur = 0; } } } };