LeetCode Easy: 58. Length of Last Word
一、题目
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World" Output: 5
输出给定字符串的最后一个单词的长度
二、解题思路
我首先想到的就是从后往前遍历给定字符串,直到遇到空格位置,计数即可,AC之后,查看了网上的做法,比我简单多了,利用的是python中的切片功能split()方法。
三、代码
#coding:utf-8
def lengthOfLastWord1(s):
"""
:type s: str
:rtype: int
"""
if s == " ":
return 0
if len(s) == 1:
return 1
j = len(s)
while s[j-1] != " ":
j-=1
# if j == 0:
# return
count = len(s) - j
print(count)
return count
def lengthOfLastWord2(s):
tmp = s.split()
if not len(tmp):
return 0
else:
print(len(tmp[-1]))
return len(tmp[-1])
if __name__ == '__main__':
s = "IndexError: string index out of range"
lengthOfLastWord2(s)
# print(s.split('i'))
# print(s.split('i',1))
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号