LeetCode(48)-Length of Last Word

题目:

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
  • 利用String.split(” “),分开成String数组。返回最后衣字符串的长度,考虑输入的字符串s为null。s= “ ”,s=“hello ”(以空格结尾)
  • -

代码:

public class Solution {
    public int lengthOfLastWord(String s) {
        if(s == null){
            return 0;
        }
        String[] ss = s.split(" ");
        int n = ss.length;
        if(n < 1){
            return 0;
        }
        String a = ss[n-1];
        if(a == null){
            return 0;
        }
        char[] aa = a.toCharArray();
        return aa.length;
    }
}
posted on 2017-08-09 12:54  ljbguanli  阅读(199)  评论(0编辑  收藏  举报