您的位置:首页 > 其它

10-Regular Expression Matching

2017-06-22 14:32 155 查看
==题目==

‘.’ 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)

Some examples:

- isMatch(“aa”,”a”) → false

- isMatch(“aa”,”aa”) → true

- isMatch(“aaa”,”aa”) → false

- isMatch(“aa”, “a*”) → true

- isMatch(“aa”, “.*”) → true

- isMatch(“ab”, “.*”) → true

- isMatch(“aab”, “c*a*b”) → true

分析

这个题真的很难··············

参考

http://blog.csdn.net/linhuanmars/article/details/21145563

思路1: 暴力解法,用到递归(目前勉强看懂了)

思路2: 动态规划,太高深~还没有看

实现

思路一:

class Solution {
public:
bool isMatch(string str1, string str2) {
//int len1 = str1.length();
//int len2 = str2.length();
//if (len1 == 0)
//  return true;
//else if (len2 == 0)
//  return false;
int i = 0, j = 0;

return matchRecursive(str1, str2, i, j);
}

bool matchRecursive(string str1, string str2, int i, int j)
{
if (j == str2.length())
return i == str1.length();
//如果str2[j+1] 不是‘*’
if (j == str2.length() - 1 || str2[j + 1] != '*')
{
if (i == str1.length() || str1[i] != str2[j] && str2[j] != '.')
return false;
else
return matchRecursive(str1,str2,i+1,j+1);
}
//如果str2[j + 1] 是‘*’
while (i < str1.length() && (str2[j] == '.' || str1[i] == str2[j]))
{
if (matchRecursive(str1, str2, i, j + 2))
return true;
i++;
}
return matchRecursive(str1, str2, i, j + 2);

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string