leetcode每日一题-58:最后一个单词的长度

leetcode每日一题-58:最后一个单词的长度

链接

最后一个单词的长度



题目

在这里插入图片描述



分析

语法题,注意结尾的多空格即可



代码

C++

class Solution {
public:
    int lengthOfLastWord(string s) {
        string res = "";
        for(int i=s.size()-1 ; i>-1 ; i--)
        {
            if(s[i] == ' ')
            {
                if(res != "") return res.size();
                res = "";
            }
            else res += string(1, s[i]);
        }

        return res.size();
    }
};

C++

class Solution {
public:
    int get(char ch)
    {
        return ch == ' ' ? 1 : 2;
    }

    int lengthOfLastWord(string s) {
        int res = 0;
        for(int i=s.size()-1 ; i>-1 ; )
        {
            int j = i - 1;
            // cout << i << "   " << get(s[i]) << endl;
            while(j > -1 and get(s[j]) == get(s[i]))
            {
                // cout << get(s[j]) << "   " << s[j] << endl;
                j--;
            } 
            if(get(s[i]) == 2)
            {
                res = i - j;
                return res;
            }
            i = j;
        }

        return res;
    }

};

Java

class Solution {
    
    
    public int lengthOfLastWord(String s) {
    
    
        int index = s.length() - 1;
        while (s.charAt(index) == ' ') {
    
    
            index--;
        }
        int wordLength = 0;
        while (index >= 0 && s.charAt(index) != ' ') {
    
    
            wordLength++;
            index--;
        }
        return wordLength;
    }
}

作者:LeetCode-Solution

Guess you like

Origin blog.csdn.net/qq_45826803/article/details/121237274