题解 | 字符串通配符
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
#include <cctype> #include <iostream> using namespace std; bool ismatch(char s1, char s2) { if (isalpha(s1) && isalpha(s2)) return s1 == s2 || (s1 - 'A' == s2 - 'a') || (s1 - 'a' == s2 - 'A'); return s1 == s2 ? true : false; } bool matchstring(string p,string s) { int i = 0, j = 0; int StarPos = -1; int match = -1; while (i < s.size()) { //当前两个字符是否相同 if (j < p.size()&&ismatch(s[i], p[j])||(p[j]=='?'&&(isalpha(s[i])||isalnum(s[i])))) { i++; j++; } //匹配到星号 else if(j < p.size()&&p[j]=='*') { StarPos=j; match=i; j=StarPos+1; } //星号用了一个但未匹配完 else if(StarPos!=-1) { match++; i=match; j=StarPos+1; } else { return false; } } while(j<p.size()&&p[j]=='*') j++; return j==p.size(); } int main() { string p, s; cin >> p >> s; if(matchstring(p,s)) cout<<"true"<<endl; else cout<<"false"<<endl; }