题目链接:591. 标签验证器
使用正则表达式简化索引和切片。
区分 outer 和 inner 两种情况的 tag。因为 outer 的最外 tag 外部不能有其它字符,因此先把外部 tag 去掉,再进行判断。
import re
class Solution:
def isValid(self, code: str) -> bool:
cdata = re.compile(r'<!\[CDATA\[.*?]]>')
code_snippet = re.compile(r'<([A-Z]{1,9})>(.*)</\1>')
tag = re.compile(r'(<[A-Z]{1,9}>|</[A-Z]{1,9}>)')
left_tag, right_tag = re.compile(r'<([A-Z]{1,9})>'), re.compile(r'</([A-Z]{1,9})>')
match = re.fullmatch(code_snippet, code)
if not match:
return False
_, inner = match.groups()
inner = re.sub(cdata, '__INVALID__', inner)
# validate inner
stack = []
for s in re.split(tag, inner):
if not s:
continue
l = re.fullmatch(left_tag, s)
if l:
stack.append(l.groups()[0])
continue
r = re.fullmatch(right_tag, s)
if r:
if stack and r.groups()[0] == stack[-1]:
stack.pop()
continue
else:
return False
if '<' in s:
return False
return not stack