题解 | #正则表达式匹配#

正则表达式匹配

https://www.nowcoder.com/practice/28970c15befb4ff3a264189087b99ad4

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @param pattern string字符串
     * @return bool布尔型
     */
    bool match(string str, string pattern) {
        // write code here
        vector<vector<bool> > dp(str.length() + 1, vector<bool>(pattern.length() + 1,
                                 false));
        dp[0][0] = true;
        for (int j = 0; j < pattern.length() + 1; j++) {
            if (pattern[j] == '*' && dp[0][j - 1] == true) {
                dp[0][j + 1] = true;
            } else if (pattern[j] == '.') {
                dp[0][j + 1] = true;
            }
        }
        for (int i = 0; i < str.length(); i++) {
            for (int j = 0; j < pattern.length(); j++) {
                if (str[i] == pattern[j]) {
                    dp[i + 1][j + 1] = dp[i][j];
                } else if (pattern[j] == '*') {
                    if (dp[i + 1][j - 1] == true || ((str[i] == pattern[j - 1]||pattern[j-1]=='.') &&
                                                     dp[i][j + 1] == true)) dp[i + 1][j + 1] = true;
                } else if (pattern[j] == '.') {
                    dp[i + 1][j + 1] = dp[i][j];
                }
            }
        }

        return dp[str.length()][pattern.length()];
    }
};

参考https://www.bilibili.com/video/BV1th411o7Rg/?buvid=Y8451886930F35C742E48A2FD95055564901&from_spmid=main.my-history.0.0&is_story_h5=false&mid=nefRmXttmtyy3nPMzFx2DA%3D%3D&p=1&plat_id=116&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=2906A950-A7FE-452D-A570-84B4C1C3D88F&share_source=COPY&share_tag=s_i&spmid=united.player-video-detail.0.0&timestamp=1698809170&unique_k=vWWk9De&up_id=646682719&vd_source=b8b29b09023805c3476ec85e1821ebfe

全部评论

相关推荐

2024-11-09 11:37
已编辑
北京航空航天大学 算法工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务