[选择语句好看但是快吗?]Length of Last Word
2015-11-03 14:30
417 查看
一、题目
Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
二、解析
返回串中最后一个单词的长度,若最后一个不是单词,则返回0。例如“hello world”返回5," "返回0, "a "返回1
思路很简单,先split(" ")存下所有单词,找到不为” “的,记为<list>ele。若ele为空,说明串中无单词,返回0;否则,返回最后一个的长度
三、代码
四、总结
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判断上,还是写完整了比较快,这样代码可读性更高,虽然要多几行吧。。
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判断上,还是写完整了比较快,这样代码可读性更高,虽然要多几行吧。。
相关文章推荐
- 人的格局与人的底线
- hdu 1874 畅通工程续(最短路Dij邻接矩阵)
- 杭电1088&zoj1099 Write a simple HTML Browser
- PreferencesFragment
- java实现图片裁切的工具类实例
- 熊孩子为什么叫我们阿姨/叔叔?
- ncurse
- iOS开发技巧:使用Xcode DEBUG模式和RELEASE模式
- 简单明了介绍Spring手工注入@autowire用法 及 beans.xml配置区别
- 并查集详解 (转)
- iOS9下App Store新应用提审攻略
- 5方与5W
- java并发编程(synchronized同步和Lock显示锁)
- bcb NumberUpDown 设置
- 图像处理质量评价标准之PSNR
- 3.6
- CoreGraphics QuartzCore CGContextTranslateCTM 用法
- 用qt编译Android应用(windows和Linux)
- Spring + Jersey构建发布Restful WebService
- 错误分析—linker command failed with exit code 1