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

大意就是找出给出字符串的最后一个单词的长度

这题比较简单,直觉上的做法就是根据空格拆分字符串,数组最后一个element的长度就是答案

  public int lengthOfLastWord(String s) {
        if(s == null || s.trim().length() == 0){
            return 0;
        }
        String[] array = s.split(" ");

        return array[array.length - 1].length();
    }

leetcode上给出了更简单的写法,思路就是用字符串的长度-lastIndexOf(" ")的位置

public int lengthOfLastWord(String s) {
    return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}

你可能感兴趣的:(Length of Last Word)