当前位置: 代码迷 >> 综合 >> leetcode Q10
  详细解决方案

leetcode Q10

热度:85   发布时间:2024-02-22 03:33:04.0

做字符串匹配问题时候,常用的二维DP的思路


class Solution {
public:bool isMatch(string s, string p){int ls = s.length()+1;int lp = p.length()+1;s.insert(0,"#");p.insert(0,"#");vector<vector<int>> dp(lp,vector<int>(ls));for(int i = 0;i<lp;i++){for(int j = 0;j<ls;j++){int flag = (i - 1 > -1) && (j - 1 > -1) ? dp[i - 1][j - 1] : ((i - 1 < 0) && (j - 1 <0)?1:0);if(flag){if(p[i]=='.'||p[i]==s[j]){dp[i][j] = 1;}else if(p[i]=='*'){if(i-2>-1&&dp[i-2][j]){dp[i][j] = 1;}else if(j-1>-1&&(p[i-1]=='.'||s[j]==p[i-1])){dp[i][j] = 1;}}}else{if(p[i]=='*'){if(i-2>-1&&dp[i-2][j]){dp[i][j] = 1;}else if(j-1>-1&&(p[i-1]=='.'||s[j]==p[i-1])&&dp[i][j-1]){dp[i][j] = 1;}}}}}return dp[lp-1][ls-1];}
};