[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的尾巴上匹配
1 package POJ; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 7 public class Main { 8 9 public static void main(String[] args) { 10 Main so = new Main(); 11 String s="AABCDEFGHIJKLMNOPQ"; 12 String p="AAB*Q**Q"; 13 System.out.println(so.isMatch(s, p)); 14 } 15 16 public boolean isMatch(String s, String p) { 17 if(s == null || p == null) 18 return false; 19 int front = p.indexOf("*"); //得到第一个*的位置,也即得到第一个*前边儿的字符个数 20 int back = p.length()-1-p.lastIndexOf("*"); //得到最后一个*后边儿还有多少个位数 21 if(front == -1){ 22 //p中没有* 23 return (s.length()==p.length())&&(iMatch(s,p)); 24 } 25 //p中有* 26 //首先,确定首尾是能满足条件的 27 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))))) 28 return false; 29 30 int i1=0; 31 int i2=0; 32 33 //现在来确定首尾的两个*中间的部分,还是以*来作为分割,一段一段地看 34 while(true){ 35 while((i2<p.length())&&(p.charAt(i2)=='*')) 36 ++i2; 37 if(i2==p.length()) 38 break; 39 int st=i2; 40 while((i2<p.length())&&(p.charAt(i2)!='*')) 41 ++i2; 42 String piece=p.substring(st,i2); //找到被*分割的片段 43 while(((i1+piece.length())<=s.length())&&!iMatch(s.substring(i1, i1+piece.length()),piece)) 44 i1++; 45 if(i1+piece.length()>s.length()) 46 return false; 47 i1=i1+piece.length(); 48 } 49 return true; 50 } 51 52 private boolean iMatch(String s, String p) { 53 // TODO Auto-generated method stub 54 for(int i=0;i<s.length();++i){ 55 if(!((s.charAt(i)==p.charAt(i))||(p.charAt(i)=='?'))) 56 return false; 57 } 58 return true; 59 } 60 }