标签:code and pos 方法 reg span false range for
方法一:
class Solution: def patternMatching(self, pattern: str, value: str) -> bool: count_a = sum(1 for ch in pattern if ch == ‘a‘) count_b = len(pattern) - count_a if count_a < count_b: count_a, count_b = count_b, count_a pattern = ‘‘.join(‘a‘ if ch == ‘b‘ else ‘b‘ for ch in pattern) if not value: return count_b == 0 if not pattern: return False for len_a in range(len(value) // count_a + 1): rest = len(value) - count_a * len_a if (count_b == 0 and rest == 0) or (count_b != 0 and rest % count_b == 0): len_b = 0 if count_b == 0 else rest // count_b pos, correct = 0, True value_a, value_b = None, None for ch in pattern: if ch == ‘a‘: sub = value[pos:pos+len_a] if not value_a: value_a = sub elif value_a != sub: correct = False break pos += len_a else: sub = value[pos:pos+len_b] if not value_b: value_b = sub elif value_b != sub: correct = False break pos += len_b if correct and value_a != value_b: return True return False
方法二:正则
class Solution: def patternMatching(self, pattern: str, value: str) -> bool: # 边界情况处理 if not pattern: return not value if len(pattern) == 1: return True # 构造正则表达式:重点是正则表达式的“后向引用” rega, regb = (‘\\1‘, ‘\\2‘) if pattern[0] == ‘a‘ else (‘\\2‘, ‘\\1‘) p = pattern.replace(‘a‘, ‘(\\w*)‘, 1).replace(‘b‘, ‘(\\w*)‘, 1).replace(‘a‘, rega).replace(‘b‘, regb) p = ‘^‘ + p + ‘$‘ m = re.match(p, value) # 匹配到 && (模式长度为1 || 模式长度为2 && 两个模式不相同) return bool(m and (len(m.groups()) == 1 or m.groups()[0] != m.groups()[1])) 作者:dz-lee 链接:https://leetcode-cn.com/problems/pattern-matching-lcci/solution/7xing-dai-ma-zheng-ze-biao-da-shi-jie-fa-python3xi/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:code and pos 方法 reg span false range for
原文地址:https://www.cnblogs.com/oldby/p/13179790.html