您的位置:首页 > 其它

Leetcode | Length of Last Word

2014-05-17 21:45 344 查看
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.

这题是要求最后一个单词的长度。而且因为输入是一个char *,而不是已经长度的数组,所以从左往右扫。碰到空格就保留它的位置。碰到非空格就计算长度。如果前面没有空格,就直接和字符串开头相比较。如果有空格就和最近的空格比较。

这种方法就可以忽略末尾是不是有空格,或者连续空格等情况了。

class Solution {
public:
int lengthOfLastWord(const char *s) {
const char *p = s, *space = NULL;
int l = 0;
for (; *p != '\0'; p++) {
if (*p == ' ') {
space = p;
} else if (space == NULL) {
l = p - s + 1;
} else {
l = p - space;
}
}
return l;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: