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)种即以空格结尾的情况。虽然解题思路简单但是考虑情况不全面,还得不断加强。


原创粉丝点击