Skip to content

Latest commit

 

History

History
179 lines (142 loc) · 3.7 KB

File metadata and controls

179 lines (142 loc) · 3.7 KB

English Version

题目描述

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

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

 

示例 1:

输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。

示例 2:

输入:s = "   fly me   to   the moon  "
输出:4
解释:最后一个单词是“moon”,长度为4。

示例 3:

输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。

 

提示:

  • 1 <= s.length <= 104
  • s 仅有英文字母和空格 ' ' 组成
  • 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;
    }
}

Go

func lengthOfLastWord(s string) int {
	if len(s) == 0 {
		return 0
	}
	space := []byte(" ")[0]
	for len(s) != 0 && s[len(s)-1] == space {
		s = s[:len(s)-1]
	}
	ret := 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] != space {
			ret++
		} else {
			return ret
		}
	}
	return ret
}

JavaScript

var lengthOfLastWord = function (s) {
    s = s.trim();
    return s.length - s.lastIndexOf(' ') - 1;
};

var lengthOfLastWord2 = function (s) {
    let res = 0;
    for (let i = 0; i < s.length; i++) {
        if (s[i] !== ' ' && (i === 0 || s[i - 1] === ' ')) {
            res = 1;
        } else if (s[i] !== ' ') {
            res++;
        }
    }
    return res;
};

TypeScript

function lengthOfLastWord(s: string): number {
    s = s.trimEnd();
    const n = s.length;
    const index = s.lastIndexOf(' ');
    if (index !== -1) {
        return n - index - 1;
    }
    return n;
}

Rust

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

...