[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 @   jianchao-li  阅读(166)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示