如何高效检测字符串中按序存在的h、e、l、l、o并返回位置?
高效检测字符串中按序存在"hello"并返回位置的实现
问题背景
需要检测字符串里是否按顺序出现h、e、l、l、o这几个字符,还要返回每个字符的位置。原来的代码嵌套了好几层if,结构太乱,想找个更高效简洁的写法。
原实现代码
import random as r # 原代码存在参数错误:r.choice需传入列表而非多个独立参数 a = r.choice(["hellooooo","hheelllloo","vhweclgljom","hqleeldo","hueqlbo"]) # 注:前三个字符串中存在按序的hello,后两个不存在 if "h" in a: i = a.index("h") if "e" in a[i:]: j = a[i:].index("e") if "l" in a[j:]: k = a[j:].index("l") if "l" in a[k:]: l = a[k:].index("l") if "o" in a[l:]: m = a[l:].index("o") print("found at",i,j,k,l,m)
高效实现方案
方法一:迭代匹配目标序列
直接遍历要找的字符序列['h','e','l','l','o'],每次从上次找到字符的下一个位置开始查找,既保证顺序,又不用嵌套一堆if,代码清爽,效率也高。
import random as r # 要匹配的目标字符序列 target_chars = ['h', 'e', 'l', 'l', 'o'] a = r.choice(["hellooooo","hheelllloo","vhweclgljom","hqleeldo","hueqlbo"]) current_start = 0 positions = [] is_found = True for char in target_chars: # 从current_start位置开始查找当前字符 char_pos = a.find(char, current_start) if char_pos == -1: is_found = False break positions.append(char_pos) # 下次从找到位置的下一位开始查找 current_start = char_pos + 1 if is_found: print(f"找到位置:{', '.join(map(str, positions))}") else: print("没找到按序的hello")
方法二:正则表达式匹配
用正则的正向预查匹配按序出现的字符,再通过捕获组计算每个字符的位置,适合熟悉正则的场景:
import random as r import re a = r.choice(["hellooooo","hheelllloo","vhweclgljom","hqleeldo","hueqlbo"]) # 正则正向预查,匹配h后接e、e后接l的按序结构 pattern = re.compile(r'(?=h)(.*?)(?=e)(.*?)(?=l)(.*?)(?=l)(.*?)(?=o)') match_result = pattern.search(a) if match_result: # 逐个计算每个目标字符的位置 h_pos = match_result.start() e_pos = h_pos + len(match_result.group(1)) + 1 first_l_pos = e_pos + len(match_result.group(2)) + 1 second_l_pos = first_l_pos + len(match_result.group(3)) + 1 o_pos = second_l_pos + len(match_result.group(4)) + 1 print(f"找到位置:{h_pos}, {e_pos}, {first_l_pos}, {second_l_pos}, {o_pos}") else: print("没找到按序的hello")
方案说明
- 方法一的好处是逻辑简单直观,时间复杂度为O(n)(n为字符串长度),每个字符最多遍历一次,效率拉满;要是以后需要匹配其他序列,只需修改
target_chars列表,扩展性很强。 - 方法二适合熟悉正则的开发者,但逻辑相对绕一些,简单匹配场景下还是方法一更实用。
内容的提问来源于stack exchange,提问作者s11010
相关产品推荐
相关产品推荐

