既然最后一篇了就拿出来用吧,返回该字符串中
AC源码
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
index = length - 1
while index >= 0 and s[index] == " ":
index -= 1
temp = index
while index >= 0 and s[index] != " ":
index -= 1
return temp - index
if __name__ == "__main__":
assert Solution().lengthOfLastWord(" ") == 0
assert Solution().lengthOfLastWord(" a") == 1
assert Solution().lengthOfLastWord(" drfish ") == 6
Length of Last Word LeetCode解题之Length of Last Word 原题 找出最后一个单词的长度。 注意点: 忽略尾部空格不存在最后一个单词时返回0 例...
原文
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.
三、尝试与结果
class Solution(object):
def lengthOfLastWord(self, s):
return len(s.strip().split(" ")[-1])
9159.com,结果:AC
换一种方法,不使用split操作。
class Solution(object):
def lengthOfLastWord(self, s):
a=0
for i in (s.strip()):
if i == " ":
a = 0
else:
a = 1
return a
结果:AC
前言
开学了,这个系列要告一段落了,感谢看过我文章的人们~
本来这篇是存在以防万一的,既然最后一篇了就拿出来用吧,偷个懒 ╮(╯▽╰)╭,所以顺序可能不太对。
LeetCode解题之Length of Last Word
翻译
给定一个包含大小写字母和空格字符的字符串,
返回该字符串中最后一个单词的长度。
如果最后一个单词不存在,返回0。
批注:
一个单词被定义为包含非空字符的字符序列。
例如,
给定 S = "Hello World",
返回 5。
二、解题
常规题,首先去除首尾空格(因为最后一个单词为最尾空格前的那个),然后用空格进行分割,取最后一个单词的长度作为答案。
代码
代码取自 Top Solution,稍作注释
public int lengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
解题思路
很简答的一道题,用Python内置函数一行就可以解决
len(s.strip().split(" ")[-1])
。自己写了一下,从后到前先忽略掉空格,再继续遍历到是空格或者遍历结束,两个者之间就是最后一个单词的长度。
分析
灵活使用find函数套装……
int lengthOfLastWord(string s) {
int index = s.find_last_not_of(' ');
return index == -1 ? 0 : index - s.find_last_of(' ', index);
}
58 Length of Last Word(最后单词的长度) 翻译 给定一个包含大小写字母和空格字符的字符串,返回该字符串中最后一个单词的长度。如...
一、题目
Length of Last Word
补充
关于 s.trim() 方法,网上有人反编译了 String
类找到这个方法看了,我给个链接,我也不知道对不对,据说这个方法不仅删首位空格符还删换行符等25种..
http://blog.csdn.net/muyu114/article/details/5734295
哈但是!这题里面就是相当于删首位空格符(中间不删),例如:
" 123 23 34 123 ".trim() = "123 23 34 123"
LeetCode Length of Last Word
LeetCode 58 Length of Last Word(最后单词的长度)
思路
看到代码只有一行的我竟无言以对 (╯°Д°)╯。
好吧我还是讲讲它的思路:
① 用 s.trim() 方法去掉了首位的空格
② 用.length()获取总长度,用 lastIndexOf(" ") 获取最后一个 " " 的index
③ 简单小学生计算得到字符串长度
原题
找出最后一个单词的长度。
注意点:
忽略尾部空格不存在最后一个单词时返回0
例子:
输入: s = “Hello world”
输出: 5
T58. Length of Last Word【Easy】
题目
给定一个由大小写字母和空格字符 ' ' 组成的字符串 s,返回字符串中最后一个单词的长度。
如果最后一个单词不存在,则返回0。
注意: 单词的定义是由非空格字符组成的字符序列。
例如,
给的 s = "Hello World"
则返回 5
本文由9159.com发布于编程,转载请注明出处:既然最后一篇了就拿出来用吧,返回该字符串中
关键词: 9159.com
下一篇:没有了