今天是紀錄LeetCode解題的第五十八天
第五十八題題目: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,傳回字串中最後一個單字的長度
單字是指僅由非空格字元組成的最長子字串
python很簡單,可以直接用split把每個空格的部分切開,直接回傳最後一個元素就好,另一個解法是先把s的尾部空白去掉(py用rstrip函式),然後從s的最後索引遍歷回去,有字元就count++,遇到空白直接break,那如果使用的程式語言沒有類似去掉尾端空白的函式,可以在判斷遇到空白要break的時候多一個條件是要滿足count > 0時才能break
用split()函式
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
去掉尾端空白rstrip()
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.rstrip()
count = 0
for i in range(len(s)-1,-1,-1):
if s[i] == " ":
break
count += 1
return count
不使用任何函式
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
for i in range(len(s)-1,-1,-1):
if not s[i] == ' ':
count += 1
elif s[i] == ' ' and count > 0:
break
return count
今天這題特別簡單,就不多做贅述