58. 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.

Example:

Input: "Hello World"
Output: 5

解题要点:

刷题以来第一次灵光乍现的题(说明还是学到东西了呀~),使用split方法把整串字符分为数组,返回最后一个数的长度。缺点是比较慢,还是需要学习新的解法。

class Solution {
    public int lengthOfLastWord(String s) {
        if(s.length() == 0 || s == null) return 0;

        String[] sc = s.split(" ");
        if(sc.length == 0) return 0;
        
        return sc[sc.length - 1].length();
    }
}

Last updated

Was this helpful?