您的位置:首页 > 编程语言 > C语言/C++

【LeetCode010算法/编程练习C++】Regular Expression Matching//挺烦的一条……

2016-12-27 16:09 423 查看


10. Regular Expression Matching

Total Accepted: 113015 
Total Submissions: 481908 
Difficulty: Hard 
Contributors: Admin

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)

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


感觉这题最关键的是把题目意思理解了……
1.首先需要注意的是:匹配的意思是,整个都一样!!互相能转化
2.“.*”匹配任意
3.X*的意思是有任意个包括0个X
4..可以替代任意一个字符
----------------------------------------------------------------------------------------------------------------
先来一个最烂的但是能解决的方法://调试了很多次……
思路:不断迭代,通过调试剔除了很多种情况……
class Solution {
public:
bool isMatch(string s, string p) {
string temp = "";
bool result=false;
if (s == "") {
if (p.size()>1 && p[1] == '*')result = isMatch(s, p.substr(2, p.size() - 2));
}
if (s == p||(p.size()==1&&p[0]=='.'&&s.size()==1))result = true;
else if (p == "")result = false;
else if (p.size() == 1 && s != p)result = false;
else if (p.size()>1&&s.size()>0) {
if ((s[0] == p[0]||p[0]=='.') && p[1] != '*')result = isMatch(s.substr(1, s.size() - 1), p.substr(1, p.size() - 1));
if ((s[0] != p[0] && p[0] != '.') && p[1] == '*')result = isMatch(s, p.substr(2, p.size() - 2));
if ((s[0] != p[0] && p[0] != '.') && p[1] != '*')result = false;
if ((s[0] == p[0] || p[0] == '.') && p[1] == '*') {
if (p[0] == '.') {
for (int i = 0; i < s.size()+1; i++) {
bool tempp = false;
tempp = isMatch(s.substr(i, s.size() - i), p.substr(2, p.size() - 2));
result += isMatch(s.substr(i, s.size() - i), p.substr(2, p.size() - 2));
}

}
else {
int n = 1, k = 1, m = 1, i = 1, ii = 0;//p里k个a,m个*。。。s里n个a
while (n < s.size() && s
== s[0]) {
n++;
}
while (m + k < p.size() && ((p[m + k] == p[0]) || p[m + k] == '*')) {
if (p[m + k] == p[0])k++;
else m++;
}
if (k - m > n)result = false;
else {
for(int a_temp=k-m;a_temp<n+1;a_temp++)
result += isMatch(s.substr(a_temp, s.size() - a_temp), p.substr(m + k, p.size() - m - k));
}
}
}
}
return result;
}

};没错,运行结果击败了0.26%的人……666ms,没runtime limited真的谢天谢地了。



再来一种Top Solution里的解决方法:  9行16ms……//肝脑涂地
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
vector<vector<bool> > dp(m + 1, vector<bool> (n + 1, false));
dp[0][0] = true;
for (int i = 0; i <= m; i++)
for (int j = 1; j <= n; j++)
if (p[j - 1] == '*')
dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
return dp[m]
;
}

};

真的好简洁…………

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