Leetcode | Length of Last Word
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 *,而不是已经长度的数组,所以从左往右扫。碰到空格就保留它的位置。碰到非空格就计算长度。如果前面没有空格,就直接和字符串开头相比较。如果有空格就和最近的空格比较。
这种方法就可以忽略末尾是不是有空格,或者连续空格等情况了。
1 class Solution { 2 public: 3 int lengthOfLastWord(const char *s) { 4 const char *p = s, *space = NULL; 5 int l = 0; 6 for (; *p != '\0'; p++) { 7 if (*p == ' ') { 8 space = p; 9 } else if (space == NULL) { 10 l = p - s + 1; 11 } else { 12 l = p - space; 13 } 14 } 15 return l; 16 } 17 };