实现rebuild_parts函数将字符串片段列表拼接为符合约束的字符串
Python实现rebuild_parts字符串拼接函数
功能需求
实现名为rebuild_parts的函数,接收一个字符串片段列表,将其重新拼接为符合指定规则的单个字符串。
拼接约束
- 输入列表中有且仅有一个以'A'开头的片段,也有且仅有一个以'Z'结尾的片段
- 返回的字符串必须以首片段开头、尾片段结尾
- 首片段定义:列表中以'A'开头的片段
- 尾片段定义:列表中以'Z'结尾的片段
- 若任意片段的末尾字符与后一片段的首字符相同,需移除其中一个重复字符,例如输入片段列表
["link","king"],拼接结果为linking
示例
输入:
mystring = rebuild_parts(["link", "king", "Apple", "ziZ", "left", "turn"])
输出:
ApplelinkinglefturnziZ
实现代码
def rebuild_parts(parts): # 定位首片段和尾片段 head = next(p for p in parts if p.startswith('A')) tail = next(p for p in parts if p.endswith('Z')) # 提取剩余片段,保留原有顺序 rest = [p for p in parts if p != head and p != tail] # 构造待拼接序列 concat_seq = [head] + rest + [tail] # 按规则拼接 result = concat_seq[0] for part in concat_seq[1:]: if result[-1] == part[0]: result = result[:-1] + part else: result += part return result
逻辑说明
- 首先从输入列表中筛选出符合要求的首片段和尾片段
- 提取输入列表中除首尾片段外的剩余元素,保持原有顺序不变
- 按照「首片段→剩余元素→尾片段」的顺序构造待拼接序列
- 遍历待拼接序列,相邻片段首尾字符重复时移除前一个片段的末尾重复字符后再拼接,无重复则直接拼接
内容的提问来源于stack exchange,提问作者bartaouch Khalid
相关产品推荐
相关产品推荐

