每日一题 2023.11.7

2586. 统计范围内的元音字符串数 - 力扣(LeetCode)

C++:

class Solution {
public:
    bool isYuan(char x){
        if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u'){
            return true;
        }
        return false;
    }
    int vowelStrings(vector<string>& words, int left, int right) {
        int res=0;
        for(int i=left;i<=right;i++){
            int l=0,r=words[i].size()-1;
            if(isYuan(words[i][l])&&isYuan(words[i][r])){
                res++;
            }
        }
        return res;
    }
};

Python:

class Solution:
    def isYuan(self,x:str)->bool:
        if x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
            return True
        return False

    def vowelStrings(self, words: List[str], left: int, right: int) -> int:
        res=0
        for i in range(left,right+1):
            l=0
            r=len(words[i])-1
            if self.isYuan(words[i][l]) and self.isYuan(words[i][r]):
                res+=1
        return res

语法解释:

self->确保指向实例对象本身的引用,将传入的参数传递给类中的方法。否则,会在全局寻找该函数。 

true->True        false->False

简洁的代码:

class Solution:
    def vowelStrings(self, words: List[str], left: int, right: int) -> int:
        return sum(
            w[0] in 'aeiou' and w[-1] in 'aeiou' for w in words[left:right+1]
        )

w[-1]代表 在w中的最后一个元素

sum->求和

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值