[lintcode easy]Length of Last Word

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.

 
Example

Given s = "Hello World", return 5.

Note

A word is defined as a character sequence consists of non-space characters only.

 

////need to consider the space in the start or the end of the string.

////use trim() to get rid of the space in the start and end.

///use new string to find out the last word's length.

 

public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
        if(s==null) return 0;
        int n=s.length();
        int res=0;
        String s1=s.trim();

            
        for(int i=s1.length()-1;i>=0;i--)
        {
            if(s1.charAt(i)==' ')
            {
                res=s1.length()-1-i;
                break;
            }
            
            if(res==0)
            {
                res=s1.length();
            }
        }
        return res;
    }
}

 

posted on 2015-11-24 06:58  一心一念  阅读(136)  评论(0编辑  收藏  举报

导航