Solution 1
public class Solution {
public int lengthOfLastWord(String s){
s = s.trim();//eliminate space characters in the head and tail
if(s == null || s.length() == 0)
return 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(s.length()-1-i) == ' ')
return i;
if(i == s.length()-1)
return i+1;
}
return -1;
}
Solution 2
public int lengthOfLastWord(String s){
return s.trim().length() > 0 ? s.split("\\s+")[s.split("\\s+").length - 1].length() : 0;
}