class Solution {
//be careful with the edge case " ", "a ", "a"
public:
int lengthOfLastWord(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool hasWordBegin = false;
int wordBegin = 0;
int wordEnd = 0;
const char* p = s;
int step = 0;
while (true)
{
char nowChracter = *(p+step);
if (nowChracter == '\0')
{
if (true == hasWordBegin)
wordEnd = step;
break;
}
if(nowChracter == ' ')
{
if (true == hasWordBegin)
wordEnd = step;
hasWordBegin = false;
}
else
{
if(false == hasWordBegin)
wordBegin = step;
hasWordBegin = true;
}
step++;
}
int len = wordEnd-wordBegin;
return len < 0 ? 0 : len;
}
};
second time
class Solution {
public:
int lengthOfLastWord(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s == NULL) return 0;
int ans = 0;
while(*s != '\0')
{
if(*s != ' ')
{
int curLen = 0;
while(*s != '\0' && *s != ' ') s++, curLen++;
ans = curLen;
}
else s++;
}
return ans;
}
};
本文介绍了一种使用C++处理字符串的方法,特别是如何计算最后一个单词的长度。通过两个不同的实现方式,展示了如何遍历字符串并识别单词边界,最终返回最后一个单词的长度。

被折叠的 条评论
为什么被折叠?



