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就行。
代码实现:
class Solution {
public int lengthOfLastWord(String s) {
if(s!=null && s.length()>0){
s = s.trim();
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i) == ' '){
return s.length()-i-1;
}
}
return s.length();
}
return 0;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
Memory Usage: 37.3 MB, less than 18.99% of Java online submissions for Length of Last Word.
Next challeng
下面在看看leetcode上别的大佬的优质解法:
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
Memory Usage: 37.1 MB, less than 21.05% of Java online submissions for Length of Last Word.
大佬真的是一行代码解决问题。