?LeetCode刷題實(shí)戰(zhàn)58:最后一個(gè)單詞的長(zhǎng)度
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做?最后一個(gè)單詞的長(zhǎng)度,我們先來(lái)看題面:
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;
????}
}
上期推文:
