[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.

指针相减

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (s == NULL)
 7             return 0;
 8             
 9         const char *start = s;
10         int len = 0;
11         while(*s != '\0')
12         {
13             if (*s == ' ')
14             {
15                 int l = s - start;                
16                 if (l != 0)
17                     len = l;
18                 start = s + 1;
19                 s++;
20             }
21             else
22                 s++;
23         }
24         
25         int l = s - start;
26         if (l != 0)
27             len = l;
28             
29         return len;
30     }
31 };

 

模拟题,每次要记录的是空格前的字符开始索引,然后遇到空格得出单词长度。最后要注意的是,可能整个字符没有空格,或者最后一个不是空格,退出循环时要检测一下。

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (s == NULL)
 7             return 0;
 8             
 9         int start = -1;
10         int index = 0;
11         int len = 0;
12         while(*s != '\0')
13         {
14            if (isalpha(*s) && start == -1)
15                start = index;
16                
17            if (isspace(*s) && start != -1)
18            {
19                len = index - start;
20                start = -1;
21            }
22            
23            s++;
24            index++;
25         }
26         
27         if (start != -1)
28             len = index - start;
29         
30         return len;
31     }
32 };
posted @ 2012-11-12 11:12  chkkch  阅读(1567)  评论(0编辑  收藏  举报