iT邦幫忙

0

leetcode寫題目測資時遇到問題.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        listt=s.split(" ")
        ans=len(listt[-1]) if len(listt[-1])!=0 else 0
        return ans

https://ithelp.ithome.com.tw/upload/images/20210201/20130307GEqnB3vhts.pnghttps://ithelp.ithome.com.tw/upload/images/20210201/20130307mLeA0HYjP8.png
測資遇到"a "時不合,請幫我看一下程式碼錯在哪?謝謝

ccutmis iT邦高手 2 級 ‧ 2021-02-01 07:38:03 檢舉
ans=len(listt[-1) if len(listt)>1 else 0
輸入'a ' 傳回0沒問題,因為題目說的是輸入字串要有空格來分割,輸出最後一個單字的長度,只輸入'a '用空格分割的結果是'a'跟'' ,''的長度是0,會不合有另一個可能原因就是題目已跟你說s能包含幾個單字用空白分隔,你輸入一個不合題意要求的內容。
buffle iT邦新手 5 級 ‧ 2021-02-01 09:57:29 檢舉
我沒有看好題目,謝謝你的解釋
ccutmis iT邦高手 2 級 ‧ 2021-02-01 10:19:34 檢舉
不客氣:)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答