码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode easy]Length of Last Word

时间:2015-11-24 07:37:58      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

[lintcode easy]Length of Last Word

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/4990432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!