您的位置:首页 > 其它

[选择语句好看但是快吗?]Length of Last Word

2015-11-03 14:30 417 查看
一、题目

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.

For example,
Given s =
"Hello World"
,
return
5
.

二、解析

返回串中最后一个单词的长度,若最后一个不是单词,则返回0。例如“hello world”返回5," "返回0, "a "返回1

思路很简单,先split(" ")存下所有单词,找到不为” “的,记为<list>ele。若ele为空,说明串中无单词,返回0;否则,返回最后一个的长度

三、代码

class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == "":
return 0

word = s.split(" ")
ele = [cur for cur in word if cur != ""]
if len(ele) == 0:
return 0
else:
return len(ele[-1])


四、总结

1.奔着简洁的目的,把最后一句改写为选择语句,即:

rst = 0 if len(ele) == 0 else len(ele[-1])

return rst

发现只打败41.16%

2.去掉rst参数,直接return,发现结果一样

3.改写为正常的if..

if len(ele) == 0:
  return 0
return len(ele[-1])

打败了84.66%

4.最终使用if..else,写完整,就打败了98.06%

看来,在If..else判断上,还是写完整了比较快,这样代码可读性更高,虽然要多几行吧。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: