Question:
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
.
Analysis:
给出一个由大小写字母和空格' '构成的字符串,返回最后一个词的长度。
如果最后一个单词不存在,则返回0.
注意:判断是否是一个单词仅仅依靠是否有空格。
思路:首先将字符串按照空格划分到一个字符数组中,然后返回数组最后一个元素的长度即可。注意特殊情况:只有空格或者字符串为空。
Answer:
public class Solution { public int lengthOfLastWord(String s) { if(s == null) return 0; String [] str = s.split(" "); if(str.length == 0) return 0; String stri = str[str.length-1]; char[] ch = stri.toCharArray(); return ch.length; } }