問題
原文
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.
内容
単語と空白を含む s が与えられます。最後の単語の長さを返してください。
単語は空白でない文字列のみを含む部分文字列です。(2行目はよくわかりませんでした。)
※正しくない可能性があります。
方針
・sの文字列の長さが0なら0を返す
・最後の部分にある空白を取り除く
・空白で分割してリストに格納し、リストの最後の文字列の長さを返す
解答
解答1
1 2 3 4 5 6 7 8 9 10 11 |
class Solution: def lengthOfLastWord(self, s: str) -> int: #sの長さが0なら0を返す if len(s)==0: return 0 #sの最後の空白を除外 s=s.strip() #sの各文字を半角空白で区切ってword_listに格納する word_list = s.split(" ") #word_listの最後の要素の長さを返す return len(word_list[-1]) |
補足・参考・感想
コメント