https://leetcode.com/problems/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.

思路:

主要是确定最后一个单词的边界。注意特殊情况。

AC代码:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int begin=-1,end=-1,j,n=s.size();
 5         for(j=n-1;j>=0;j--)
 6             if(s[j]!=' '){
 7                 begin=j;
 8                 break;
 9             }
10         if(begin==-1)
11             return 0;
12         for(j=begin;j>=0;j--){
13             if(s[j]==' '){
14                 end=j+1;
15                 break;
16             }
17         }
18         if(end==-1)
19             end=0;
20         return begin-end+1;
21     }
22 };