Skip to content

Latest commit

 

History

History
112 lines (84 loc) · 2.41 KB

File metadata and controls

112 lines (84 loc) · 2.41 KB

English Version

题目描述

给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

 

示例 1:

输入:s = "Hello World"
输出:5

示例 2:

输入:s = " "
输出:0

 

提示:

  • 1 <= s.length <= 104
  • s 仅有英文字母和空格 ' ' 组成

解法

Python3

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        last_word_length = 0
        meet_word = False
        for i in range(len(s) - 1, -1, -1):
            ch = ord(s[i])
            if ch >= 65 and ch <= 122:
                meet_word = True
                last_word_length += 1
            elif meet_word:
                break
        return last_word_length

Java

class Solution {
    public int lengthOfLastWord(String s) {
        int n = s.length();
        int lastWordLength = 0;
        boolean meetWord = false;
        for (int i = n - 1; i >= 0; --i) {
            char ch = s.charAt(i);
            if (ch >= 'A' && ch <= 'z') {
                meetWord = true;
                ++lastWordLength;
            } else if (meetWord) {
                break;
            }
        }
        return lastWordLength;
    }
}

Rust

impl Solution {
    pub fn length_of_last_word(s: String) -> i32 {
        let s = s.trim_end();
        if s.len() == 0 {
            return 0;
        }
        for (i, c) in s.char_indices().rev() {
            if c == ' ' {
                return (s.len() - i - 1) as i32;
            }
        }
        s.len() as i32
    }
}

...