Wildcard Matching
Implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). 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", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false
思想:用变量start记录*是否出现过;用ix和iy表示*可能比配的字符,即下一次需要匹配的开端
- public boolean isMatch(String s, String p) {
- int s1 = s.length();
- int p1 = p.length();
- if(s1==0) {
- for(int i=0;i<p1;i++) {
- if(p.charAt(i) != '*') {
- return false;
- }
- }
- return true;
- }
- boolean star = false;
- int ix = 0;
- int iy = 0;
- int i= 0;
- int j=0;
- for(i=0,j=0;i<s1;i++,j++) { //完全匹配s1
- char ptmp = '#'; //java中无结尾字符
- if(j<p1)
- ptmp = p.charAt(j);
- switch(ptmp){
- case '?':
- break;
- case '*':
- ix = i;
- iy = j;
- star = true;
- while(iy<p1 && p.charAt(iy) == '*') iy++;
- if(iy==p1) return true;
- i = ix - 1;
- j = iy - 1;
- break;
- default:
- if(ptmp!=s.charAt(i)) {
- if(!star) {
- return false;
- }
- ix++;
- i = ix -1;
- j = iy - 1;
- }
- }
- }
- while(j<p1 && p.charAt(j) == '*') j++;
- if(j==p1) {
- return true;
- } else {
- return false;
- }
- }
C代码:
- bool isMatch(const char *s, const char *p) {
- bool star = false;
- const char *str,*ptr;
- for(str = s,ptr=p;*str!='\0';str++,ptr++)
- {
- switch(*ptr)
- {
- case '?':
- break;
- case '*':
- star=true;
- s=str;
- p=ptr;
- while(*p=='*')
- p++;
- if(*p=='\0')
- return true;
- str=s-1;
- ptr=p-1;
- break;
- default:
- {
- if(*str!=*ptr)
- {
- if(!star)
- return false;
- s++;
- str=s-1;
- ptr=p-1;
- }
- }
- }
- }
- while(*ptr=='*')
- ptr++;
- return (*ptr=='\0');
- }