首页 > 其他 > 详细

LeetCode -- Length of Last Word

时间:2015-10-07 20:23:28      阅读:209      评论:0      收藏:0      [点我收藏+]

Question:

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.

 

Analysis:

给出一个由大小写字母和空格‘ ‘构成的字符串,返回最后一个词的长度。

如果最后一个单词不存在,则返回0.

注意:判断是否是一个单词仅仅依靠是否有空格。

思路:首先将字符串按照空格划分到一个字符数组中,然后返回数组最后一个元素的长度即可。注意特殊情况:只有空格或者字符串为空。

 

Answer:

public class Solution {
    public int lengthOfLastWord(String s) {
        if(s == null)
            return 0;
        String [] str = s.split(" ");
        if(str.length == 0)
            return 0;
        String stri = str[str.length-1];
        char[] ch = stri.toCharArray();
        return ch.length;
    }
}

 

LeetCode -- Length of Last Word

原文:http://www.cnblogs.com/little-YTMM/p/4859175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!