正则排序
按照查到的思路,代码如下
迭代的方式完成
bool isMatch(string s, string p) {
if(p.empty()) return s.empty();
bool first_match = !s.empty() && (p[0] == s[0] || p[0] == '.');
if(p.length() >= 2 && p[1] == '*')
return isMatch(s, p.substr(2)) || (first_match && isMatch(s.substr(1), p));
else
return first_match && isMatch(s.substr(1), p.substr(1));
}
正在尝试的思路目前遇到的问题 在遇到".*"后,如果后面的刚好与该点一致,会导致后面的出现问题
已知问题如下:
s = “dede” p = ".*de"弹出false
代码如下
bool isMatch(string s, string p) {
if (p.empty()) return s.empty() ? true : false;
int sP = p.size();
if (s.empty()) {
for (int r = 0; r < sP - 1; ++r) {
if (p[r] != '*' && p[r + 1] == '*') ++r;
else return false;
}
}
int sS = s.size();
int pS = 0, pP = 0;
for (int sTmp = 1; sTmp < sP - 1; ++sTmp) {
if (p[sTmp] == '*' && p[sTmp - 1] == p[sTmp + 1]) {
p[sTmp] = p[sTmp + 1];
p[sTmp + 1] = '*';
//cout << p << "Check is Right Change" << endl;
}
}
for (; pS < sS && pP < sP;) {
//cout << pS << ',' << pP << " Original Point Check-Point" << endl;
if (p[pP] == '.') {
if (pP + 1 < sP && p[pP + 1] == '*') {
pP += 2;
if (!p[pP]) {
pS = sS;
break;
}
else {
//cout << "in" << pP << endl;
//cout << (s.find(p[pP], pS) == -1 ? "true" : "false");
//cout << (int)s.find(p[pP], pS) << endl;
if (s.find(p[pP], pS) == -1) break;
else {
cout << "in" << pP << endl;
pS = s.find(p[pP], pS) + 1;
//cout << pS << "Check-Point pS s.find line43" << endl;
pP++;
if (p[pP] == '*') {
while (pS < sS && s[pS - 1] == s[pS]) pS++;
pP++;
}
}
}
}
else {
pP++;
pS++;
}
}
else{
//cout << s[pS] << ",,," << p[pP] << endl;
if (s[pS] != p[pP]) {
//cout << "Check is False but Next is *" << endl;
if (pP + 1 < sP && p[pP + 1] == '*')pP += 2;
else return false;
}
else {
if (pP + 1 < sP && p[pP + 1] == '*') {
while (pS + 1 < sS && s[pS] == s[pS + 1])pS++;
pS++;
pP += 2;
}
else {
pS++;
pP++;
}
}
}
//cout << pS << "," << pP << " Over Point Check-Point" << endl;
}
if (pS >= sS) {
for (int r = pP; r < sP; ++r) {
//cout << p[pP] << endl;
if (p[r] != '*' && p[r + 1] == '*') {
++r;
pP += 2;
}
else if (p[pP] == s.back()) {
string tmp;
tmp.push_back(s[sS - 1]);
tmp.push_back('*');
if (p.substr(0, pP).find(tmp) != -1) {
pP++;
//cout << pP << "much" << endl;
}
}
else break;
}
}
if (pP < sP || pS < sS)return false;
else return true;
}