Skip to content

Latest commit

 

History

History
169 lines (138 loc) · 3.57 KB

File metadata and controls

169 lines (138 loc) · 3.57 KB

中文文档

Description

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

 

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Solutions

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
    }
}

...