[Easy] 58. Length of Last Word
发布日期:2021-05-07 18:21:07 浏览次数:9 分类:原创文章

本文共 713 字,大约阅读时间需要 2 分钟。

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"Output: 5

Solution

Brute Force

4 ms 6.5 MB

class Solution {   public:    int lengthOfLastWord(string s) {            int len = 0, tail = s.length() - 1;        while (tail >= 0 && s[tail] == ' ') tail--;        while (tail >= 0 && s[tail] != ' ') {               len++;            tail--;        }        return len;    }};
上一篇:[Easy] 66. Plus One
下一篇:[Easy] 53. Maximum Subarray

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月11日 03时44分59秒