您的位置:首页 > 其它

[LeetCode]Length of Last Word

2013-05-29 19:43 435 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: