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.

 

Analyse: Considering the situation s.t. the last few numbers of the string are all ' ' .

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int len = s.length() - 1;
 5         int result = 0;
 6         
 7         while(s[len] == ' ') len--;
 8         
 9         for(int i = len; i >= 0; i--){
10             if(s[i] != ' ') result++;
11             else break;
12         }
13         return result;
14     }
15 };

 

posted @ 2015-04-17 13:45  amazingzoe  阅读(115)  评论(0)    收藏  举报