[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",
return5.

思路:要求最后一个单词的长度,首先想到的当然是从后往前开始遍历,若遇到空格或者下标等于0了,就返回单词的个数就行,但是,这样想忽略了一个问题,若是,字符串最后有空格怎么办?如: s ="Hello World    ",所以应该是从后往前遍历的时候,先跳过空格,直到遇到第一个非空格的字符,才开始计数。代码如下:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) 
 4     {
 5         int res=0;
 6         int len=strlen(s);
 7         if(s==NULL) return 0;
 8         int i=len-1;
 9         while(s[i]==' ')
10             i--;
11         while(s[i] !=' '&&i>=0)
12         {
13             i--;
14             res++;
15         }    
16         return res;    
17     }
18 };

 

posted @ 2017-06-25 16:50  王大咩的图书馆  阅读(205)  评论(0编辑  收藏  举报