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->求和