美文网首页ACM题库~
LeetCode 58. Length of Last Word

LeetCode 58. Length of Last Word

作者: 关玮琳linSir | 来源:发表于2017-09-25 15:27 被阅读10次

    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.

    题意,找到,最后一个' '后面的单词,求出它的长度,如果没有,就返回0。

    思路:从后向前遍历,发现是字母了,触发标识位,如果还是字母继续,发现' '直接停止,返回刚才的单词的长度。

    java代码:

    public int lengthOfLastWord(String s) { 
            if(s==null || s.length() == 0)
                return 0;
         
            int result = 0;
            int len = s.length();
         
            boolean flag = false;
            for(int i=len-1; i>=0; i--){
                char c = s.charAt(i);
                if((c>='a' && c<='z') || (c>='A' && c<='Z')){
                    flag = true;
                    result++;
                }else{
                    if(flag)
                        return result;
                }
            }
         
            return result;
        }
    

    相关文章

      网友评论

        本文标题:LeetCode 58. Length of Last Word

        本文链接:https://www.haomeiwen.com/subject/gkhdextx.html