题目描述:
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.
中文理解:给出一个字符串,由如果个单词组成,每个单词之间用空格分割,求最后一个单词的长度。
解题思路:异常判断:字符串为null或者全部由空格组成,返回为0;字符串使用空格分割,返回最后一个单词的长度。
代码(java):
class Solution {
public int lengthOfLastWord(String s) {
if (s==null)return 0;
String [] str=s.split(" ");
if(str.length==0)return 0;
return str[str.length-1].length();
}
}