题目地址:https://leetcode.com/problems/length-of-last-word/description/open in new window

题目描述

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

Ifthe last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Examle:

input:

"Hello World"
"Hello World "
"Hello W orld"
"Hello Wo   rld"

output:

5
5
4
3

题目大意

计算一个字符串中,最后一个不为空的单词的长度。

解题方法

库函数

使用库函数,方法比较简单,一行代码。

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.strip().split(' ')[-1])
                

1 2 3 4 5 6 7 8

双指针

使用两个指针,一个指向最后一个字符串的结尾,一个指向最后一个字符串的开头。

Python代码如下:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        N = len(s)
        left, right = 0, N - 1
        while right >= 0 and s[right] == " ":
            right -= 1
        left = right
        while left >= 0 and s[left] != " ":
            left -= 1
        return right - left

1 2 3 4 5 6 7 8 9 10 11 12 13 14

C++代码如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int N = s.size();
        int left = 0, right = N - 1;
        while (right >= 0 && s[right] == ' ') right--;
        left = right;
        while (left >= 0 && s[left] != ' ') left--;
        return right - left;
    }
};

1 2 3 4 5 6 7 8 9 10 11

单指针

使用一个指针也可以完成上面的操作。代码比较简单,不解释了。

Python版本如下:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        N = len(s)
        count = 0
        for i in range(N - 1, -1, -1):
            if s[i] == " ":
                if count == 0:
                    continue
                else:
                    break
            else:
                count += 1
        return count

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

C++版本如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int N = s.size();
        int count = 0;
        for (int i = N - 1; i >= 0; --i) {
            if (s[i] == ' ') {
                if (count != 0) {
                    break;
                }
            } else {
                count++;
            }
        }
        return count;
    }
};

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发