LeetCode刷题实战58:最后一个单词的长度
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 最后一个单词的长度,我们先来看题面:
https://leetcode-cn.com/problems/length-of-last-word/
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
题意
样例
输入: "Hello World"
输出: 5
解题
class Solution {
public int lengthOfLastWord(String s) {
if(s==null || s.length()==0)
return 0;
int len = s.length();
int count = 0;
for(int i=len-1;i>=0;i--){
if(s.charAt(i)!=' '){
count++;
}else if(s.charAt(i)==' '&& count!=0){
return count;
}
}
return count;
}
}
上期推文: