标签:
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
.
Given s = "Hello World"
, return 5
.
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