NOTE

正则表达式

支持 . 和 * 的正则表达式匹配。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。

‘.’ 匹配任意单个字符 ‘*’ 匹配零个或多个前面的那一个元素 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。

2. 思路

3. 实现

package main

func isMatch(s string, p string) bool {
	return isMatchDFS(s, p)
}

func isMatchDFS(s string, p string) bool {
	if p == "" {
		return s == ""
	}

	isFirstMatch := len(s) > 0 && (p[0] == '.' || p[0] == s[0])
	isMatchAny := len(p) > 1 && p[1] == '*'

	if isMatchAny {
		return isMatchDFS(s, p[2:]) || (isFirstMatch && isMatchDFS(s[1:], p))
	} else {
		return isFirstMatch && isMatchDFS(s[1:], p[1:])
	}
}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看