leetcode : Length of Last Word
runtime 0 ms, beats 100% of cpp submissions
O(n) solution with explanation
tags: string
🔗 link
📖 description
給定一個字串,回傳最後一個字詞的長度。
ex. Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
🧠 solution
模擬操作,從後方遍歷陣列,找到第一個詞。
⏳ time complexity
最差狀況下遍歷整個字串,時間複雜度 O(n)
總時間複雜度 O(n)
📝 code
1 | class Solution { |