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
.
理解题意,如果没有空格则输出字符长度。注意" a a "," ","a a"等情况。
使用split处理,非常容易。
package leetcode;
public class LengthofLastWord {
public int lengthOfLastWord(String s) {
int ans = 0;
String[] strs = s.split(" ");
if (strs.length > 0 ){
ans = strs[strs.length-1].length();
}
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new LengthofLastWord().lengthOfLastWord(""));
}
}