【競技プログラミング】「Length Of Last Word」with Python | LeetCode #36

Python

こちらは「Length Of Last Word」のPythonによる解答例となっております。この問題は、与えられた文字列の最後の単語の長さを返す問題です。

問題

文字列 s が与えられた場合、最後の単語の長さを返します。最後の単語は、単語と単語の間に1つ以上のスペースがある場合に定義されます。

  • s には、英字と空白文字のみが含まれます。
  • s の長さは、1以上であり、10^4以下です。

解法

この問題は、Pythonの文字列操作を用いた1つのアプローチがあります。文字列をスペースで分割し、最後の単語を取得してその長さを返す方法を用います。

アルゴリズムの概要を以下に述べます。

  1. 文字列 s をスペースで分割します。
  2. 最後の単語を取得します。
  3. 最後の単語の長さを返します。

Pythonコード

以下のコードが、「Length of Last Word」を解くためのPythonプログラムとなります。

### Function ##################################################################

def solve(num=0):
    
    solver  = Solution().lengthOfLastWord
    
    if 1 <= num <= Input().input: id_LIST = [num]
    else: id_LIST = [id+1 for id in range(Input().input)]
    
    for id in id_LIST:
        data    = Input(id)
        ans     = solver(data.s)
        result  = "OK" if ans==data.ans else "NG"
        print(f"[{str(id).zfill(3)}] {result}")

### Class #####################################################################

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

#==============================================================================

class Input:
    
    def __init__(self, num=0):
        
        if num == 1:
            self.s = "Hello World"
            self.ans    = 5
        
        elif num == 2:
            self.s = "   fly me   to   the moon  "
            self.ans    = 4

        elif num == 3:
            self.s = "luffy is still joyboy"
            self.ans    = 6
        
        else:
            self.input  = 3

### Main ######################################################################

if __name__ == "__main__":

    solve()

###############################################################################