58. Length of Last Word
来源:互联网 发布:电脑屏幕冷暖调节软件 编辑:程序博客网 时间:2024/06/06 15:50
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
.
问题描述:给定一个只包含大小写字母和空格的字符串,返回最后一个word的长度。如果最后一个word不存在,则返回0。word定义为不包含空格的字符序列,及只包含字母。
分析:遍历字符串,定义一个变量统计word的长度len,如果是字母,则len++;如果遇到空格,则len清零重新统计长度。同时要考虑以下三种特殊情况:
(1)字符串为空,即字符串长度为0时:直接返回0;
(2)字符串由若干个空格组成时:使用trim() 函数移除字符串两侧的空白字符,如果移除后的字符串为空,则可判断该字符串全由空格组成,返回0;
(3)字符串以空格结尾:首先同样使用trim() 函数移除字符串两侧的空白字符,然后循环遍历使用trim()函数处理后得到的字符串,按分析的思路来统计长度。
public class Solution { public int lengthOfLastWord(String s) { if(s.length()==0 || s.trim().isEmpty()) return 0; int len = 0; String s1 = s.trim(); for(int i =0;i<s1.length();i++){ if(s1.charAt(i)!=' ') len++; else{ len = 0; } } return len; }}
刚开始读懂题目时思路就很清楚,很快就就按自己的思路编好了程序,提交代码后才发现自己忘了考虑特殊情况中的第(2)种即以空格结尾的情况。虽然解题思路简单但是考虑情况不全面,还得不断加强。
阅读全文
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
- JS实现图片变换
- ADB常用命令记录
- SQLServer 杂记
- HQL查询详细语法讲解
- wamp配置虚拟主机
- 58. Length of Last Word
- 丑数
- Dev Express 中GridControl导出为PDF时出现中文乱码现象的解决办法
- 字符编码的历史故事
- rails:simple_for 对于关联模型的特殊技巧
- 6月书讯:最受欢迎的SQL入门书重磅升级
- 人生,总会有不期而遇的温暖,和生生不息的希望
- 【漏洞分析】MS17-010:深入分析“永恒之蓝”漏洞
- Java实现从m个各不相同的元素中取出n个,并进行全排列