编写函数:查找打印传入数组中含3个字母表连续顺序字母的单词
符合规则的单词打印函数实现
核心判定逻辑
- 遍历输入的单词数组,直到遇到
Null(对应语言的空结束标记)终止运行 - 对每个单词先做前置校验:长度不足3的短词直接跳过
- 逐位滑动检查所有连续3字符的组合,只要存在任意一组满足后一字符ASCII值 = 前一字符ASCII值+1(即字母表顺次连续,如s-t-u、a-b-c、x-y-z这类),就判定为符合要求
- 符合要求的单词直接打印输出
代码实现(C语言版本)
适配C语言中字符串指针数组以NULL作为结束标记的常规场景:
#include <stdio.h> #include <string.h> #include <ctype.h> void printConsecutiveThreeWords(char *words[]) { for (int idx = 0; words[idx] != NULL; idx++) { char *currentWord = words[idx]; int wordLen = strlen(currentWord); if (wordLen < 3) continue; int isMatch = 0; // 遍历所有连续3字符的窗口 for (int i = 0; i <= wordLen - 3; i++) { // 若需兼容大小写,可先将字符转为小写再计算差值 char c1 = tolower(currentWord[i]); char c2 = tolower(currentWord[i+1]); char c3 = tolower(currentWord[i+2]); if (c2 - c1 == 1 && c3 - c2 == 1) { isMatch = 1; break; } } if (isMatch) { printf("%s\n", currentWord); } } }
代码实现(Python版本)
适配Python中列表以None作为结束标记的场景:
def print_consecutive_three_words(words: list) -> None: for word in words: # 遇到结束标记直接终止遍历 if word is None: break if len(word) < 3: continue is_match = False # 滑动窗口检查所有连续三元组 for i in range(len(word) - 2): # 兼容大小写的比较逻辑 c1 = word[i].lower() c2 = word[i+1].lower() c3 = word[i+2].lower() if ord(c2) - ord(c1) == 1 and ord(c3) - ord(c2) == 1: is_match = True break if is_match: print(word)
测试验证
传入测试数组:
["costume", "cost", "abc", "hello", "xyz", "ab", None]
输出结果:
costume
abc
xyz
完全匹配题目规则:cost仅存在s-t两个连续字符,不满足3个连续的要求,不会被输出。
内容的提问来源于stack exchange,提问作者Holiday-Pineapple
相关产品推荐
相关产品推荐

