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.

Example:

Input: "Hello World"
Output: 5

Thinking:

class Solution {
    public int lengthOfLastWord(String s) {
        String[] ss = s.trim().split(" ");
        return ss[ss.length - 1].length();
    }
}

二刷

总是觉得这道题目应该有些问题,例如我输入” Hello 12”, 答案和获得的结果是不一样的但是还是可以AC

class Solution {
    public int lengthOfLastWord(String s) {
        if(s == null || s.trim().length() == 0) return 0;
        String[] arr = s.trim().split(" ");
        if(arr.length == 1)  return s.trim().length();
        return arr[arr.length - 1].length();
    }
}