首页 > 其他 > 详细

【leetcode】Length of Last Word

时间:2015-01-31 19:25:28      阅读:286      评论:0      收藏:0      [点我收藏+]

前段时间忙平台访问分析的统计库开发,有一个多月没写java了。。找找手感,刷刷题吧。。

去leetcode上挑了个简单的,题目是这样的。

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.

解决方案如下:

public class Solution {
    public int lengthOfLastWord(String s) {
        String[] arr=s.split(" ");
        if(arr.length==0){
            return 0;
        }
        return arr[arr.length-1].length();
    }
}
将给定字符串s根据空格进行分隔,共有两种情况:

1、s是一堆空格构成的“空串”,调用split方法会返回一个长度为0的空数组。

2、s中有word,分隔之后取最后一个即可~


【leetcode】Length of Last Word

原文:http://blog.csdn.net/exceptional_derek/article/details/43342693

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