[Leetcode58]最后一个单词的长度

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

python:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)
        if n == 0:
            return 0
        while s[n - 1] == ' ':
            n -= 1
            if n == 0:
                return 0
        i = n - 1
        res = 0
        while i >= 0:
            if s[i] != ' ':
                res += 1
                i -= 1
            else:
                break
        return res

C++: 

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n = s.length();
        if(n == 0) return 0;
        while(s[n - 1] == ' '){
            n -= 1;
            if(n == 0) return 0;
        }
        int i = n - 1,res = 0;
        while(i >= 0){
            if(s[i] != ' '){
                res += 1;i -= 1;
            }
            else break;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/84642942
今日推荐