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.
Example:
Input: "Hello World" Output: 5
Solution:
There can be tailing spaces, e.g. “abc “, we need to trim the string first and then scan the string in reverse order until a space or reach the beginning of the string.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public: int lengthOfLastWord(string s) { int i = s.length() - 1; int l = 0; while (i >= 0 && s[i] == ' ') --i; while (i >= 0 && s[i] != ' ') { --i; ++l; } return l; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment