【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         int total_len = strlen(s);
 5         if (total_len == 0) return 0;
 6         int ret = 0, i = total_len - 1;
 7         while (i >= 0 && s[i] == ' ') --i;
 8         while (i >= 0 && s[i] != ' ') {
 9             ++ret;
10             --i;
11         }
12         return ret;
13     }
14 };
View Code

按题意数就可以了..

posted @ 2014-05-20 12:10  小菜刷题史  阅读(97)  评论(0编辑  收藏  举报