前段时间忙平台访问分析的统计库开发,有一个多月没写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,分隔之后取最后一个即可~