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

最后一个单词的长度。首先去除最后面多余的空格,trim。然后找到最后一个空格后面的单词的位置。

class Solution {
    public int lengthOfLastWord(String s) {
        s=s.trim();
        int index=s.lastIndexOf(" ")+1;
        return s.length()-index;
    }
}

 


posted on 2017-12-19 15:42  夜的第八章  阅读(117)  评论(0编辑  收藏  举报

导航