题目描述:
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.
Example:
Input: "Hello World"
Output: 5
题目解释:
给出一句话,每个单词之间用' '分开,返回最后一个单词的长度。如果没有单词,则返回0。
注意:单词被定义为仅由非空间字符组成的字符序列。
题目解法:
1.我的解法。首先通过' '对这句话进行分割,然后判断String数组长度,String数组长度是0说明没有单词,否则取出数组最后一个字符串,返回这个字符串的长度。
class Solution {
public int lengthOfLastWord(String s) {
String[] array = s.split(" ");
if(array.length == 0) return 0;
String temp = array[array.length - 1];
return temp.length();
}
}