[LeetCode] Length of Last Word

Well, the basic idea is very simple. Start from the tail of s and move backwards to find the first non-space character. Then from this character, move backwards and count the number of non-space characters until we pass over the head of s or meet a space character. The count will then be the length of the last word.

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) { 
 4         int len = 0, tail = s.length() - 1;
 5         while (tail >= 0 && s[tail] == ' ') tail--;
 6         while (tail >= 0 && s[tail] != ' ') {
 7             len++;
 8             tail--;
 9         }
10         return len;
11     }
12 };

 

posted @ 2015-06-28 16:11  jianchao-li  阅读(164)  评论(0编辑  收藏  举报