统计范围内的元音字符串数(函数)
两种写法
第一种
int vowelStrings(char** words, int wordsSize, int left, int right) {
int count = 0; // 初始化计数器
// 遍历给定范围内的字符串数组
for (int j = left; j <= right; j++) {
int t = strlen(words[j]); // 获取当前字符串的长度
// 检查当前字符串是否以元音字母开头
if (words[j][0] == 'a' || words[j][0] == 'e' || words[j][0] == 'i' || words[j][0] == 'o' || words[j][0] == 'u') {
// 如果以元音字母开头,再检查是否以元音字母结尾
if (words[j][t - 1] == 'a' || words[j][t - 1] == 'e' || words[j][t - 1] == 'i' || words[j][t - 1] == 'o' || words[j][t - 1] == 'u') {
count++; // 如果是以元音字母开头并以元音字母结尾的字符串,则计数器加1
}
}
}
return count; // 返回计数结果
}
第二种
int isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; // 判断字符是否为元音字母
}
int vowelStrings(char** words, int wordsSize, int left, int right) {
int count = 0; // 初始化计数器
for (int j = left; j <= right; j++) { // 遍历给定范围内的字符串数组
int t = strlen(words[j]); // 获取当前字符串的长度
if (t == 0) continue; // 如果字符串长度为0,则跳过当前循环
if (t == 1) { // 如果字符串长度为1
if (isVowel(words[j][0])) { // 检查字符是否为元音字母
count++; // 如果是元音字母,则计数器加1
}
} else { // 如果字符串长度大于1
if (isVowel(words[j][0]) && isVowel(words[j][t - 1])) { // 检查首尾字符是否均为元音字母
count++; // 如果首尾字符均为元音字母,则计数器加1
}
}
}
return count; // 返回计数结果
}