作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/length-of-last-word/description/

题目描述

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.

Examle:

input:

"Hello World"
"Hello World "
"Hello W orld"
"Hello Wo rld"

output:

5
5
4
3

题目大意

计算一个字符串中,最后一个不为空的单词的长度。

解题方法

库函数

使用库函数,方法比较简单,一行代码。

class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.strip().split(' ')[-1])

双指针

使用两个指针,一个指向最后一个字符串的结尾,一个指向最后一个字符串的开头。

Python代码如下:

class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
left, right = 0, N - 1
while right >= 0 and s[right] == " ":
right -= 1
left = right
while left >= 0 and s[left] != " ":
left -= 1
return right - left

C++代码如下:

class Solution {
public:
int lengthOfLastWord(string s) {
int N = s.size();
int left = 0, right = N - 1;
while (right >= 0 && s[right] == ' ') right--;
left = right;
while (left >= 0 && s[left] != ' ') left--;
return right - left;
}
};

单指针

使用一个指针也可以完成上面的操作。代码比较简单,不解释了。

Python版本如下:

class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
count = 0
for i in range(N - 1, -1, -1):
if s[i] == " ":
if count == 0:
continue
else:
break
else:
count += 1
return count

C++版本如下:

class Solution {
public:
int lengthOfLastWord(string s) {
int N = s.size();
int count = 0;
for (int i = N - 1; i >= 0; --i) {
if (s[i] == ' ') {
if (count != 0) {
break;
}
} else {
count++;
}
}
return count;
}
};

日期

2017 年 8 月 24 日
2018 年 11 月 24 日 —— 周日开始!一周就过去了~

最新文章

  1. CI Weekly #6 | 再谈 Docker / CI / CD 实践经验
  2. 2015.4.24 移动端,chrome不兼容或无法运行的一些具体问题
  3. git的一些命令行
  4. shell编程之流程控制
  5. gnuplot conditional plotting: plot col A:col B if col C == x
  6. strcpy vs memcpy
  7. 修改SQL Server 2005 数据库文件名字
  8. Python笔记 001
  9. C# MVC 实现登录的5种方式
  10. php strpos 用法实例教程
  11. wechat客户端修改
  12. Sql2008中使用DataTable作为存储过程的参数
  13. Web Service-- 使用 JDK 发布 WS
  14. PHP移动互联网开发(1)——环境搭建及配置
  15. 字符设备驱动4: ioremap
  16. Codeforces Round #300(A.【字符串,多方法】,B.【思维题】,C.【贪心,数学】)
  17. C#版 - Leetcode 306. 累加数 - 题解
  18. javaScript---RegExp
  19. Oracle 10046
  20. C# ModBus Tcp读写数据 与服务器进行通讯

热门文章

  1. R语言与医学统计图形【4】直方图、金字塔图
  2. Linux服务器I/O性能分析-1
  3. 开始读 Go 源码了
  4. C语言中的字符和整数之间的转换
  5. day 03Linux修改命令提示符
  6. Output of C++ Program | Set 17
  7. App内容分享
  8. error信息
  9. JavaScript实现数组去重方法
  10. 结合redis缓存的方式,查询和展示分类信息