leetcode算法每天一题010: 正则表达式,判断pattern和string是否匹配(动态规划DP)

本文介绍了一种解决正则表达式匹配问题的算法,通过动态规划方法实现了字符串与正则表达式的高效匹配。文中详细解释了状态转移方程及边界条件,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PATTERNTRUEFALSE
a.baab,abb,acba, ab,b
a*bb,ab,aab,aaaba,abb,acb
c*a.baab,caab,cccccacb,ccabbbaab,cabbb

  • dp[i] [j] 的含义是当字符串 s 的长度为 i,模式串 p 的长度为 j 时,两者是否匹配

  • 同一行往前走两个代表的是 a* 等于 空 ,此时, dp[i] [j] = dp[i] [j – 2]

  • 如果当前的字符和之前的字符一样,也是可以match的,只需要看看这match的部分之前是否是match的即可,也就是去看
    dp[i-1][j-2]
    又因为当前为
    的情况 dp[i] [j] = dp[i] [j – 2],可以dp[i-1][j]

在这里插入图片描述

 https://alchemist-al.com/algorithms/regular-expression

class Solution {
public:
    bool isMatch(string s, string p) {
        int dp[s.length()+1][p.length()+1];
        int m, n ;m= s.length();n =  p.length(); 
        //初始化
        memset(dp,0,sizeof(dp));//https://blog.youkuaiyun.com/weixin_44807751/article/details/103793473
        dp[0][0]= true;
        
        for(int j=1;j<n+1;j++){//对第一行的所有列进行初始化
            if (p[j-1] == '*')
                dp[0][j] = dp[0][j-2];
            else
                dp[0][j] = false;
        }

        // 继续填写
        for(int i=1;i<m+1;i++){
            for(int j=1;j<n+1;j++){
                if (p[j-1]=='.' || p[j-1]==s[i-1]){

                        dp[i][j] =dp[i-1][j-1];

                }else if(p[j-1]=='*' && j>=2){
                    if(p[j-2] == s[i-1] || p[j-1-1]=='.'){
                        dp[i][j] = dp[i-1][j] || dp[i][j-2];
                    }else{
                        dp[i][j] =  dp[i][j-2];
                    }
                }else{
                    dp[i][j] = false;
                }
            }
        }
        return dp[m][n];
    }
};

在这里插入图片描述

参考与更多

  • 暴力匹配做法 执行用时:0 ms, 在所有 C 提交中击败了100.00%的用户
bool isMatch(char * s, char * p)
{
    int slen = strlen(s);
    int plen = strlen(p);
    char c;
    int i,j;
    int ret;
    
    if(slen == 0 && plen != 0 && *(p + 1) != '*')
    {//如果s串已空而p串不可能空,不匹配
        return 0;
    }
    if(plen > 0 && *(p + 0) == '.')
    {//如果p串第一个字符是'.'
        if(plen > 1 && *(p + 1) == '*')
        {//如果p串第二个字符是'*'
            //跳过带'*'的字串,*(p + j)第一个不跟'*'的字符
            for(j = 2; j + 1 < plen && *(p + j + 1) == '*'; j += 2);

            if(plen == j)
            {//p串已经到了末尾
                return 1;
            }
            else
            {
                for(i = 0; i < slen; i ++)
                {//考虑到'.*'的特殊性只能挨个将字串与之尝试匹配
                    if(*(s + i) == *(p + j) || *(p + j) == '.')
                    {
                        if(isMatch(s + i, p + j))
                        {
                            return 1;
                        }
                    }
                }
                return 0;
            }
        }
        else//'.'匹配到任意字符
        {

            return isMatch(s + 1,  p + 1);
        }
    }
    else if(plen > 0)
    {
        //如果p串第一个字符是非'.'的字符
        if(plen > 1 && *(p + 1) == '*')
        {
            //如果p串第二个字符是'*'
            //跳过与p串首字符相等且带'*'的字串,*(p + j)第一个不跟'*'或不与p串首字符相等的字符
            for(j = 2; j + 1 < plen && *(p + j) == *(p + 0) && *(p + j + 1) == '*'; j += 2);
            //
            if(plen == j)
            {
                //p串已经到了末尾
                for(i = 0; i < slen && *(s + i) == *(p + 0); i ++);
                if(i == slen) 
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                //考虑到带'*'的特殊性只能挨个将字串与之尝试匹配
                for(i = 0; i < slen && *(s + i) == *(p + 0); i ++)
                {
                    if(isMatch(s + i, p + j))
                    {
                        return 1;
                    }
                }
                return isMatch(s + i, p + j);
            }
        }
        else if(*s == *p)
        {//两个字串首字符相等匹配到任意字符
            return isMatch(s + 1,  p + 1);
        }
        else return 0;
    }
    //p串空后根据s串的剩余长度判断结果
    if(slen > 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

  • 逆推法
  • 状态归纳+边界条件
public static int uniquePaths(int m, int n) {
    if (m <= 0 || n <= 0) {
        return 0;
    }

    int[][] dp = new int[m][n]; // 
    // 初始化
    for(int i = 0; i < m; i++){
      dp[i][0] = 1;
    }
    for(int i = 0; i < n; i++){
      dp[0][i] = 1;
    }
        // 推导出 dp[m-1][n-1]
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = dp[i-1][j] + dp[i][j-1];
        }
    }
    return dp[m-1][n-1];
}

视频图解 动态规划 正则表达式

  • 用两个指针顺序读取是无法实现的,因为不知道*需要匹配几个(需依次比较,当某个不匹配时即为匹配的个数)。

添加链接描述

添加链接描述

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        
        auto first_match = !s.empty() && (s[0] == p[0] || p[0] == '.');
        
        if (p.length() >= 2 && p[1] == '*') {
            return isMatch(s, p.substr(2)) || (first_match && isMatch(s.substr(1), p));
        } else {
            return first_match && isMatch(s.substr(1), p.substr(1));
        }
    }

https://blog.youkuaiyun.com/ResumeProject/article/details/127430933

### AC 自动机算法简介 AC 自动机是一种多模匹配算法,能够高效处理多个模式串的匹配问题。该算法基于前缀树(Trie),并引入失败指针的概念来加速查询过程[^1]。 对于给定的一组模式串,在构建 Trie 后会通过广度优先遍历设置每个节点的失败指针指向最长公共前后缀的位置。当遇到不匹配的情况时,可以沿失败指针跳转继续尝试匹配而无需回溯输入序列中的位置。这种特性使得 AC 自动机非常适合用于解决涉及大量关键字快速检索的应用场景。 ### LeetCode 上的相关题目分析 #### 题目一:实现 Trie (前缀树) 虽然这不是严格意义上的 AC 自动机应用案例,但掌握如何创建操作 Trie 是理解更复杂的 AC 自动机的基础。本题要求设计一个简单的字典树结构支持插入、搜索以及部分词根匹配功能[^4]。 ```python class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end_of_word = True def search(self, word: str) -> bool: node = self.root for char in word: if char not in node.children: return False node = node.children[char] return node.is_end_of_word def startsWith(self, prefix: str) -> bool: node = self.root for char in prefix: if char not in node.children: return False node = node.children[char] return True ``` #### 题目二:加权随机选择 此题并非直接关于 AC 自动机,但它展示了如何利用数据结构优化特定类型的查询效率。考虑到实际应用场景中可能存在的权重因素,这类技巧也可以应用于改进 AC 自动机性能[^2]。 然而,这里并没有给出具体的代码片段或详细的解释说明其与 AC 自动机的关系,因此建议关注更加贴合主题的例子。 #### 题目三:通配符匹配 尽管这道题主要讨论的是正则表达式的变体形式——通配符匹配,其中涉及到的状态转移机制实际上与有限状态机(FSM),进而也与 AC 自动机有着密切联系。两者都依赖于预定义的状态转换表来进行字符串匹配[^3]。 ```python def isMatch(s: str, p: str) -> bool: dp = [[False] * (len(p)+1) for _ in range(len(s)+1)] dp[-1][-1] = True for i in range(len(s), -1, -1): for j in range(len(p)-1, -1, -1): match = i < len(s) and p[j] in {s[i], '?'} if j+1 < len(p) and p[j+1] == '*': dp[i][j] = dp[i][j+2] or match and dp[i+1][j] else: dp[i][j] = match and dp[i+1][j+1] return dp[0][0] ``` ### 实现完整的 AC 自动机 为了更好地展示 AC 自动机的工作原理及其优势所在,下面提供了一个简化版 Python 版本: ```python from collections import deque class ACAutomaton: class Node: def __init__(self): self.transitions = {} # 子结点映射 self.fail = None # 失败指针 self.output = [] # 输出列表 def __init__(self): self.root = self.Node() def add_pattern(self, pattern): current_node = self.root for symbol in pattern: if symbol not in current_node.transitions: new_node = self.Node() current_node.transitions[symbol] = new_node current_node = current_node.transitions[symbol] current_node.output.append(pattern) def build_fail_links(self): queue = deque([self.root]) while queue: parent = queue.popleft() for child_symbol, child in parent.transitions.items(): if parent == self.root: child.fail = self.root else: parent_fail = parent.fail while parent_fail != self.root \ and child_symbol not in parent_fail.transitions: parent_fail = parent_fail.fail if child_symbol in parent_fail.transitions: child.fail = parent_fail.transitions[child_symbol] else: child.fail = self.root fail_node = child.fail child.output.extend(fail_node.output) queue.append(child) def find_matches(self, text): matches = [] state = self.root for index, character in enumerate(text): while state != self.root and character not in state.transitions: state = state.fail if character in state.transitions: state = state.transitions[character] output_list = state.output.copy() for matched_string in output_list: start_index = index - len(matched_string) + 1 end_index = start_index + len(matched_string) matches.append((start_index, end_index)) return matches ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值