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

For example,
Given s = "Hello World",
return 5.

代码分析:

public class Solution {
    public int lengthOfLastWord(String s) {
        if(s.length() == 0) return 0;
        s = s.trim();
        int len = s.length();
        int count = 0;
        for(int i = len-1 ; i >=0 ; i--){
            if(s.charAt(i) == ' ') break;
            else count ++;
        }
        return count;
    }
}

注意:处理字符串时,需要用到的几个方法:

1、strim()

2、忽略大小写(把大写 -> 小写)

3、substring(start,end)  ,含头不含尾

4、'z' = 'Z' +32;

 

posted @ 2016-04-24 13:26  wangb021  阅读(133)  评论(0编辑  收藏  举报