LeetCode 10 - Regular Expression Matching

前端之家收集整理的这篇文章主要介绍了LeetCode 10 - Regular Expression Matching前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、问题描述

Description:

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s,const char *p)

Forexamples:

  1. isMatch("aa","a") false
  2. isMatch("aa","aa") true
  3. isMatch("aaa","aa") false
  4. isMatch("aa","a*") true
  5. isMatch("aa",".*") true
  6. isMatch("ab",".*") true
  7. isMatch("aab","c*a*b") true

实现正则表达式匹配,匹配字符'.''*'

  • '.'匹配任何单个的字符。
  • '*'前面的字符重复 ≥ 0 次。


@H_403_184@二、解题报告

对于上面的 example,可能有人会对isMatch("ab",".*") → true产生疑问,我的理解是*可以将.重复多次,而.可以表示任意单个字符,所以结果是正确的。

这里提供两种解法:递归法 和 动态规划法

1. 递归法

使用递归进行判断时,总体上可以分成两种情况:一种是以'*'开头的,另一种不是。

  1. class Solution {
  2. public:
  3. bool isMatch(string s,string p) {
  4. int lens = s.length();
  5. int lenp = p.length();
  6. if(lenp == 0)
  7. return lens == 0;
  8.  
  9. if(lenp==1 || p[1]!='*') // 第二个字符不是'*'
  10. {
  11. if(lens<1 || (s[0]!=p[0] && p[0]!='.'))
  12. return false;
  13. return isMatch(s.substr(1,lens-1),p.substr(1,lenp-1));
  14. }
  15. else // 第二个字符是'*'
  16. {
  17. int i=-1;
  18. while(i<lens && (i<0 || p[0]=='.' || p[0]==s[i]))
  19. {
  20. if(isMatch(s.substr(i+1,lens-i-1),p.substr(2,lenp-2)))
  21. return true;
  22. ++i;
  23. }
  24. return false;
  25. }
  26. }
  27. };

2. 动态规划法

dp[i][j] 表示字串s[i...len(s)]p[j...len(p)]是否可以匹配。

  1. class Solution {
  2. public:
  3. bool isMatch(string s,string p) {
  4. int ls = s.length();
  5. int lp = p.length();
  6. vector<vector<bool>> dp(ls+1,vector<bool>(lp+1,false));
  7.  
  8. dp[0][0] = true; // 初始化
  9. for(int i = 1; i < lp && p[i] == '*'; i+=2){
  10. dp[0][i+1] = true;
  11. }
  12.  
  13. for(int i = 1; i <= ls; ++i){
  14. for(int j = 1; j <= lp; ++j){
  15. if(p[j-1] == '.' || p[j-1] == s[i-1])
  16. dp[i][j] = dp[i-1][j-1];
  17. else if(j > 1 && p[j-1] == '*')
  18. dp[i][j] = dp[i][j-2] || (dp[i-1][j] && (p[j-2] == '.' || s[i-1] == p[j-2])); // .*
  19. }
  20. }
  21. return dp[ls][lp];
  22. }
  23. };





LeetCode答案源代码https://github.com/SongLee24/LeetCode

猜你在找的正则表达式相关文章