iT邦幫忙

0

leetcode with python:58. Length of Last Word

題目:

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.

給定一個字串,回傳最後一個單字的長度
ex:input:"Hello World"=>output: 5
Explanation:The last word is "World" with length 5.

這題用簡單的字串操作可以很簡短

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s=s.split()
        return len(s[-1])

用split將裡面單字化作陣列
然後回傳最後一項得長度即可
最後執行時間28ms(faster than 95.93%)

當然,我們還是得用一下正當一點的解法,不要這樣蒙混過關

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        if " " not in s: #若無空格該單字即為最後一項單字
            return len(s)
            
        i=len(s)-1
        ans=0
        while s[i]==" ":
            i=i-1
        while i>=0 and s[i]!=" ":
            ans=ans+1
            i=i-1
        return ans

我們從字串後往前看,找到第一個非空格字元(即最後一個單字的最後一個字)
由此開始算字元長度,直到遇到" "或index值超出範圍
此時長度即為最後一個單字的長度
最後執行時間33ms(faster than 86.27%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言