且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Length of Last Word

更新时间:2022-06-08 19:44:49

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 };