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.

思路:从尾巴开始扫,扫到第一个不是空格的字母停止。再继续扫,更新长度,扫到空格结束。

public class Solution {
    public int lengthOfLastWord(String s) {
    int index=s.length()-1;
    int count=0;
    while(index>=0&&s.charAt(index)==' ')
    {
        index--;
    }
    while(index>=0&&s.charAt(index)!=' ')
    {
    index--;
    count++;
    }
    return count;
}
}

投机取巧做法:

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

 

posted on 2016-10-11 14:53  Machelsky  阅读(111)  评论(0编辑  收藏  举报