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;

态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5426862.html