题目来源:
https://leetcode.com/problems/length-of-last-word/description/
题目分析:
本题是给定我们一个字符串,让我们返回最后一个非空字符的长度,需要注意空格也算是一个字符。当时我考虑的时候是想从头开始遍历,用sheng来存储遍历的非空字符,遇到空格,则sheng='',从头开始计数。这时我没有考虑到最后一个非空字符后可以有多个空格,此时会返回‘’而非正确的结果。看到其他人的想法才觉得。。。果然思维很重要。有的人是这样想的。从最后开始遍历,当遇到第一个非空字符时开始计数,到遇到空字符时停止计数。
此时我写的代码为:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s=s[::-1];count=0;i=0
if(len(s)==0):
return 0
else:
while((i<=(len(s)-1))and (s[i]==' ')):%%这里需要注意要时刻注意i不要超过下标的界限,并且要把它放在and前面先进行比较
i += 1
while((i<=(len(s)-1))and(s[i]!=' ')):
count = count + 1
i = i+1
return count
然后还有人用到了split函数,可以预防下标出界的问题,也可以使程序更简单运行更快。
下面先来介绍一下split函数。
描述
Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串语法
split()方法语法:str.split(str="", num=string.count(str)).
参数
str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。num -- 分割次数。
返回值
返回分割后的字符串列表。
实例
以下实例展示了split()函数的使用方法:#!/usr/bin/python
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
以上实例输出结果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
再来介绍一下strip()函数
描述
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。语法
strip()方法语法:str.strip([chars]);
参数
chars -- 移除字符串头尾指定的字符。返回值
返回移除字符串头尾指定的字符生成的新字符串。
实例
以下实例展示了strip()函数的使用方法:实例(Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "0000000 Runoob 0000000";
print str.strip( '0' ); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
以上实例输出结果如下:
Runoob
Runoob
则此时的代码可以写成:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s=s[::-1]
s=s.strip().split(' ')
return len(s[0])