58. Length of Last Word
来源:互联网 发布:周芷若结局 知乎 编辑:程序博客网 时间:2024/04/29 23:13
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
.
题意:求给定字符串的最后一个单词的长度。
解题思路就是,从后向前遍历,碰到空格字符停止,得到长度;
题目非常简单,只需要注意几种特殊情况即可:
1.字符串为空
2.字符串末尾为空格字符' '
下面是代码:
public class Solution { public int lengthOfLastWord(String s) { int num = 0; int k = s.length()-1; while(k>=0 && s.charAt(k) == ' ') k--; if(k == -1) return 0; for(int i=k;i>=0;i--){ if(s.charAt(i) != ' ') num++; else break; } return num; }}
public int lengthOfLastWord(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1;}是不是特别简单,Stirng的trim()方法返回的的是一个去除字符串两端空格的字符串。
阅读全文
0 0
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58.Length of Last Word
- springmvc中的返回值
- CA总线(二)
- javaweb学习总结(四)——Http协议
- laravel笔记-Eloquent ORM(基础)
- android UDP通信
- 58. Length of Last Word
- 一张图了解Confluence中的模块注入/实例化
- Linux系统常见的压缩命令与打包命令
- eclipse中使用maven创建项目JDK版本默认是1.5解决方法
- Html-2.图片和连接
- 丑数
- Unity 工作经历+近期面试经历
- Linux 设备驱动概述
- git学习笔记整理-7-打标签