オットセイの経営日誌

データサイエンス系ベンチャーを経営してます。経営のこと、趣味のことつぶやきます。

LeetCode / Length of Last Word

https://leetcode.com/problems/length-of-last-word/

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

If the last word does not exist, return 0.

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

Example:

Input: "Hello World"
Output: 5

Discussionで'This problem is not fun at all'とか言われちゃってましたが、、、LeetCodeは個人的にはなかなか難易度高い問題も多いので、こういう箸休め的問題は欲しいなと思います。
英単語で構成された文の中で、末尾の単語の長さを返す問題です。

解答・解説

解法1

リストlsに対して、2つのポインタとなる変数slow, fastを用意し、slowは末尾の単語の末尾を、fastは末尾の単語の先頭のインデックスを返すように計算します。
末尾の単語の長さを判定するので、リストを逆向きにループさせていきます。
まず、slowは初期値を-1とします。list[-1]とするとlistの末尾の要素を示すのは自明ですね。そこから逆向きにループさせて、ブランクでない位置まで辿ります。
通常、'Hellow World'のように末尾の単語の後ろにブランクはなく、slowは初期値の-1のまま(ループは進まない)になることが多いと思います。

ls = len(ls)
slow = -1
while slow >= -ls and s[slow] == ' ':
    slow -= 1

次に、fastは初期値をslowと同値とします。そこから逆向きにループさせて、ブランクの位置まで辿ります。

fast = slow
while fast >= -ls and s[fast] != ' ':
    fast -= 1

最後に、slow - fastとすれば、末尾の単語の長さを計算できます。
まとめると以下のようになります。

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        ls = len(s)
        slow = -1
        while slow >= -ls and s[slow] == ' ':
            slow -= 1
        fast = slow
        while fast >= -ls and s[fast] != ' ':
            fast -= 1
        return slow - fast
解法2

1 line solutionを示して、今日は終わります。rstripで文末の余計なブランクを剥ぎ取ってしまうという力技。

class Solution:
    def lengthOfLastWord(self, s):
        return len(s.rstrip(' ').split(' ')[-1])