[LeetCode 10] 正則表示式匹配
阿新 • • 發佈:2022-01-16
給你一個字串s和一個字元規律p,請你來實現一個支援 '.'和'*'的正則表示式匹配。
'.' 匹配任意單個字元
'*' 匹配零個或多個前面的那一個元素
所謂匹配,是要涵蓋整個字串s的,而不是部分字串。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/regular-expression-matching
這裡不考慮巢狀的閉包,因此設計狀態 (i,j),考慮三種轉移(匹配、跳出閉包、重複閉包),BFS 即可
class Solution { public: bool isMatch(string s, string p) { int n=s.length(); int m=p.length(); queue<pair<int,int>> que; vector<vector<int>> vis(n+2,vector<int>(m+2)); que.push({0,0}); vis[0][0]=1; auto checkValid=[&](int i,int j)->bool { return i>=0 && i<=n && j>=0 && j<=m; }; auto pushState=[&](int i,int j)->void { if(!checkValid(i,j)) return; if(vis[i][j]==true) return; vis[i][j]=true; que.push({i,j}); }; while(!que.empty()) { auto [i,j]=que.front(); que.pop(); if(i==n&&j==m) return true; if(j==m) continue; if(i<n && s[i]==p[j] || p[j]=='.') { pushState(i+1,j+1); } if(j+1<m && p[j+1]=='*') { pushState(i,j+2); } if(j>0 && p[j]=='*') { pushState(i,j-1); } } return false; } };