Skip to content

Instantly share code, notes, and snippets.

@egraldlo
Last active August 29, 2015 14:06
Show Gist options
  • Save egraldlo/7c85ad1fec10e2088b58 to your computer and use it in GitHub Desktop.
Save egraldlo/7c85ad1fec10e2088b58 to your computer and use it in GitHub Desktop.
length of last word
class Solution {
public:
int lengthOfLastWord(const char *s) {
int len=0;
/* 字符串的遍历方式,始终这样写,下面肯定要有个s++ */
while(*s!='\0'){
/* 当本字符不是空格的时候,+1 */
if(*s!=' ')
len++;
/* 如果本字符等于空格,而下一个字符不等于空格的时候,重新开始计数 */
if(*s++==' '&& *s!=' ' && *s!='\0')
/* 一种特殊情况需考虑,空格后面马上是结束符,那个时候也不应该清零,还是前面的长度 */
len=0;
/* 连续多个空格的时候,还保持上一次的len */
}
return len;
/* 如果输入为空, 直接返回0
如果输入为空格,直接返回0 */
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment