[Leetcode] 0058. 最后一个单词的长度

58. 最后一个单词的长度

题目描述

给你一个字符串 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 中至少存在一个单词

解法

方法一:反向遍历

题目要求得到字符串中最后一个单词的长度,可以反向遍历字符串,寻找最后一个单词并计算其长度。

由于字符串中至少存在一个单词,因此字符串中一定有字母。首先找到字符串中的最后一个字母,该字母即为最后一个单词的最后一个字母。

从最后一个字母开始继续反向遍历字符串,直到遇到空格或者到达字符串的起始位置。遍历到的每个字母都是最后一个单词中的字母,因此遍历到的字母数量即为最后一个单词的长度。

时间复杂度 \(O(n)\),空间复杂度 \(O(1)\)。其中 \(n\) 为字符串 \(s\) 长度。

Python3

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        index = len(s)-1
        wordlength =0
        while(s[index]==' '):
            index -=1
        while(index >=0 and s[index]!=' '):
            wordlength +=1
            index -=1
        return wordlength

C++

class Solution {
public:
    int lengthOfLastWord(string s) {
        int index = s.size() -1;
        
        while(s[index] == ' '){
            index--;
        }
        int wordLength = 0;
        while(index >=0 && s[index] != ' '){
            wordLength++;
            index--;
        }
        return wordLength;
    }
};

方法二:逆向遍历 + 双指针

从字符串 \(s\) 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 \(i\)。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 \(j\)。那么最后一个单词的长度即为 \(i - j\)

时间复杂度 \(O(n)\),空间复杂度 \(O(1)\)。其中 \(n\) 为字符串 \(s\) 长度。

Python3

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while i >= 0 and s[i] == ' ':
            i -= 1
        j = i
        while j >= 0 and s[j] != ' ':
            j -= 1
        return i - j

C++

class Solution {
public:
    int lengthOfLastWord(string s) {
        int i = s.length() - 1;
        while (i >= 0 && s[i] == ' ') --i;
        int j = i;
        while (j >= 0 && s[j] != ' ') --j;
        return i - j;
    }
};
posted @ 2023-10-17 20:18  野哥李  阅读(91)  评论(0编辑  收藏  举报