[Leetcode] Wildcard Matching

时间:2023-03-09 16:12:42
[Leetcode] 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 Solution 1:
贪心算法:
http://blog.unieagle.net/2012/11/07/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Awildcard-matching/ 只需要依据连续的’*’,将p分割成一些不带’*’的子串。然后在s中依次匹配就好了,只不过需要特殊照顾一下首尾两个子串:
1.对于开头不是’*’的p,第一个子串必须从s[0]开始匹配
2.对于结尾不是’*’的p,最后一个子串必须在s的尾巴上匹配
 package POJ;

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; public class Main { public static void main(String[] args) {
Main so = new Main();
String s="AABCDEFGHIJKLMNOPQ";
String p="AAB*Q**Q";
System.out.println(so.isMatch(s, p));
} public boolean isMatch(String s, String p) {
if(s == null || p == null)
return false;
int front = p.indexOf("*"); //得到第一个*的位置,也即得到第一个*前边儿的字符个数
int back = p.length()-1-p.lastIndexOf("*"); //得到最后一个*后边儿还有多少个位数
if(front == -1){
//p中没有*
return (s.length()==p.length())&&(iMatch(s,p));
}
//p中有*
//首先,确定首尾是能满足条件的
if(!( (front+back<=s.length())&&(iMatch(s.substring(0, front),p.substring(0, front)))&&(iMatch(s.substring(s.length()-back),p.substring(p.length()-back)))))
return false; int i1=0;
int i2=0; //现在来确定首尾的两个*中间的部分,还是以*来作为分割,一段一段地看
while(true){
while((i2<p.length())&&(p.charAt(i2)=='*'))
++i2;
if(i2==p.length())
break;
int st=i2;
while((i2<p.length())&&(p.charAt(i2)!='*'))
++i2;
String piece=p.substring(st,i2); //找到被*分割的片段
while(((i1+piece.length())<=s.length())&&!iMatch(s.substring(i1, i1+piece.length()),piece))
i1++;
if(i1+piece.length()>s.length())
return false;
i1=i1+piece.length();
}
return true;
} private boolean iMatch(String s, String p) {
// TODO Auto-generated method stub
for(int i=0;i<s.length();++i){
if(!((s.charAt(i)==p.charAt(i))||(p.charAt(i)=='?')))
return false;
}
return true;
}
}