leetcode:Length of Last Word(求最后一个单词长度)

Question :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.

问题:给定一个字符串包含大小写字符和空格字符,返回字符串中最后一个单词的长度,如果最后一个单词不存在,返回0,单词之间用空格分开,没有空格的,整个字符串算作一个单词。

思路:这个题很简单,最主要的是要考虑的各种边界条件,(1)考虑s="" s=NULL 情况 (2) 考虑s="a  "情况(3)考虑s="Hello"情况(4)考虑s="d"情况

代码设计:

 1 int lengthOfLastWord(const char *s) {
 2 
 3     int length = strlen(s);
 4     int index = length - 1;
 5     int count = 0;
 6     if (NULL == s ||!length) //字符串如果为空或者没有字符 返回0
 7         return 0;
 8     while (*(s + index) == ' ')//从最后一个非空格的字符开始往前遍历
 9         index--;
10     while (*(s+index)!=' '&&index>=0)   //从后往前,直到遇到空格
11         count++,index--;
12     return count;
13 }

 

 

 

posted @ 2014-06-21 17:49  般若一号  阅读(497)  评论(0编辑  收藏  举报