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 *,而不是已经长度的数组,所以从左往右扫。碰到空格就保留它的位置。碰到非空格就计算长度。如果前面没有空格,就直接和字符串开头相比较。如果有空格就和最近的空格比较。
这种方法就可以忽略末尾是不是有空格,或者连续空格等情况了。
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; } };
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- [LeetCode] Length of Last Word
- leetcode Length of Last Word
- LeetCode | Length of Last Word
- LeetCode_Length Of Last Word
- 【LeetCode with Python】 Length of Last Word
- [leetcode]Length of Last Word
- LeetCode - Length of Last Word
- leetcode: Length of Last Word
- LeetCode_Length of Last Word
- LeetCode Length of Last Word
- leetcode 21: Length of Last Word
- leetcode 21: Length of Last Word
- leetcode:Length of Last Word
- [Leetcode 3] 58 Length of Last Word
- LeetCode: Length of Last Word
- [leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode]Length of Last Word
- [leetcode]Length of Last Word