[leetcode]#58. Length of Last Word
来源:互联网 发布:mac cosmetics美国官网 编辑:程序博客网 时间:2024/05/19 15:22
- 题目翻译
给定一个字符串s,只包含大小写字母和空格字符 ’ ‘,返回该字符串中最后一个单词的长度。如果不存在最后一个单词返回0。
注意:所谓单词,是指仅由非空格字符组成的字符序列。比如,给定s= “Hello World”,返回 5。 - 思路方法
利用Python的内置函数string.rstrip()和string.split()。先将字符串后面的空格部分删除,再按照空格字符将剩余部分分成若干部分,此时最后一部分即为最后一个单词(也可能是”),直接返回其长度即可。 - Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格)
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ return len(s.rstrip().split(' ')[-1])
- 与上面类似,不过不再用内置string处理函数了,在删除后面的空格后,从后面开始数非空格字符的个数,即为所求。
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ length, j = 0, len(s)-1 while j>=0: if s[j] != ' ': break j = j - 1 for i in xrange(j, -1, -1): if s[i] == ' ': return length length = length + 1 return length
阅读全文
0 0
- 58. Length of Last Word Leetcode Python
- [LeetCode]58.Length of Last Word
- LeetCode --- 58. Length of Last Word
- [Leetcode] 58. Length of Last Word
- [leetcode] 58.Length of Last Word
- LeetCode - 58. Length of Last Word
- <LeetCode OJ> 58. Length of Last Word
- 58. Length of Last Word LeetCode
- 【LeetCode】58. Length of Last Word
- leetcode 58. Length of Last Word
- LeetCode *** 58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode-58. Length of Last Word
- LeetCode-58.Length of Last Word
- [leetcode] 58. Length of Last Word
- LeetCode 58. Length of Last Word
- Leetcode-58. Length of Last Word
- leetcode-java-58. Length of Last Word
- Android Jni 利用transpose()和flip()函数实现图像旋转90°
- jQuery ajax请求错误返回status 0和错误error的问题
- 关于ICE传输文件大小的限制跟踪
- The Accomodation of Students (着色法)
- 原型模式
- [leetcode]#58. Length of Last Word
- git代码提交步骤
- 1.3.3.序列化操作
- Android 中内存泄漏的原因和解决方案
- jqueryeasyui 遮罩层mask
- hibernate 中 Provided id of the wrong type for class 异常
- 关于sql行转列的整理
- Django框架MTV架构之 Models(模型)
- idea 快捷键 与eclipse的差别