友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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

代码还是要力求简洁明了!

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
 * Memory Usage: 38 MB, less than 7.57% of Java online submissions for Length of Last Word.
 *
 * Copy from: https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/[画解算法:58. 最后一个单词的长度 - 最后一个单词的长度 - 力扣(LeetCode)]
 */
public int lengthOfLastWord(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
        return 0;
    }
    int end = s.length() - 1;
    while (end >= 0 && s.charAt(end) == ' ') {
        end--;
    }
    if (end < 0) {
        return 0;
    }
    int start = end;
    while (start >= 0 && s.charAt(start) != ' ') {
        start--;
    }
    return end - start;
}

/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
 * Memory Usage: 37.3 MB, less than 48.48% of Java online submissions for Length of Last Word.
 */
public int lengthOfLastWordFor(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
        return 0;
    }
    int start = s.length(), end = s.length();
    for (int i = s.length() - 1; i >= 0; i--) {
        char c = s.charAt(i);
        if (end == s.length() && c != ' ') {
            end = i;
        }
        if (c == ' ' && i < end && end != s.length()) {
            start = i;
            break;
        }
    }
    if (start == s.length() && end != s.length()) {
        start = -1;
    }
    return end - start;
}