
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
.
解题思路1:
遍历字符串,设置整形变量n,记录当前遍历到的无空格子串的长度,如果子串后遇到空格,且空格后再次遇到新的子串,则更新n,否则返回n;
注意:
本题容易忽略的是,返回最后一个子串的长度,不能简单想做遇到空格就重新计数,因为可能空格后不再有子串了,也就是最后一个子串结束后,字符串没有完,还有空格存在。因此要注意对这种情况进行判断。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.size();
int len_lw = ; for (int i = ; i < len; ++i) {
if (i != && s[i-] == ' ' && s[i] != ' ')
len_lw = ;
if (s[i] != ' ')
len_lw++;
} return len_lw;
}
};
解题思路2:
直接从后遍历字符串,先过滤尾部的空格,之后遍历的第一个子串长度就是要返回的结果。
class Solution {
public:
int lengthOfLastWord(const char *s) {
int len = strlen(s);
int sum = ; while (s[len-] == ' ')
len--; for (int i=len-; i>=; i--) {
if(s[i]!=' ')
sum++;
else
break;
} return sum;
}
};
附录:
1、C语言中的char* char const char 和C++ string的关系
2、C++中对字符串操作的函数总结
3、灵活运用字符串指针,多用指针操作,少用数组操作:
class Solution {
public:
int lengthOfLastWord(const char* s) {
int len = ; while (*s) {
if (*s++ != ' ')
++len;
else if (*s && *s != ' ')
len = ;
} return len;
}
};