如何给嵌套括号内的所有内容加引号并转换为标题大小写格式
可行实现方案
采用栈深度标记+内容缓存的思路单次遍历字符串即可完成处理,无需正则替换,时间复杂度为O(n),执行效率较高,完整实现如下:
def wrap_values_within_group(s: str, delimiter_group='()'): start_char, end_char = delimiter_group res = [] depth = 0 in_bracket_buf = '' for c in s: if c == start_char: # 处理此前缓存的括号内文本 if depth > 0 and in_bracket_buf: res.append(in_bracket_buf.title()) in_bracket_buf = '' res.append(f'{start_char}"') depth += 1 elif c == end_char: # 处理当前缓存的括号内文本 if in_bracket_buf: res.append(in_bracket_buf.title()) in_bracket_buf = '' res.append(f'"{end_char}') depth -= 1 else: if depth == 0: # 括号外文本直接保留 res.append(c) else: # 括号内文本先缓存 in_bracket_buf += c # 兼容未闭合括号的异常场景,可根据需求调整 if in_bracket_buf and depth > 0: res.append(in_bracket_buf.title()) return ''.join(res)
测试验证
# 简单场景测试 print(wrap_values_within_group('hello(world)')) # 输出:hello("World") # 嵌套括号场景测试 print(wrap_values_within_group('hi (hello(world(a test)))')) # 输出:hi ("Hello("World("A Test")")")
内容的提问来源于stack exchange,提问作者Wizard.Ritvik
相关产品推荐
相关产品推荐

