首页 > 学院 > 开发设计 > 正文

[LeetCode] Length of Last Word

2019-11-15 01:05:54
字体:
来源:转载
供稿:网友
[LeetCode] Length of Last Word

Given a stringsconsists 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,Givens="Hello World",return5.

这道题个人觉得很简单的哈。

重点就是要想一个办法来判定这是不是最后一个word,什么时候最后一个word结束。

因为我们重点是最后一个word,所以写loop的时候就从后头往前。那么最简单判定一个单词是否结束的方法就是,判断这个字母的下一个字符依旧是字母还是是别的什么符号,如果不是字母,那就表示这个单词已经写完啦。

但是要注意就是有一个比较特殊的情况。如果从后面先是从空格开始然后才是单词呢。所以针对这个要额外多写一个if statement哈。

另外就是注意字母区分大小写的哈。

所以想通了这个,就很好写了。

public class Solution {    public int lengthOfLastWord(String s) {        //specail case        if(s==null){           return 0;         }        int count=0;        for(int i=s.length()-1;i>=0;i--){            char c=s.charAt(i);                        if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){                count++;            }else{                if(count==0){                    count=0;                }else{                return count;                }            }        }        return count;            }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表