您的位置:首页 > 其它

leetcode 83: Wildcard Matching

2013-02-21 04:59 363 查看
Wildcard MatchingMar
16 '12

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


uncompleted

public class Solution {
public boolean isMatch(String s, String p) {
// Start typing your Java solution below
// DO NOT write main() function
if(p.length() == 0) return s.length()==0 ? true : false;

int i=0;
char c;
while(i<p.length() && i<s.length() && (c=p.charAt(i)) != '*') {
if( c!='?' && c!=s.charAt(i) ) return false;
i++;
}

int j=s.length()-1;
int k=p.length()-1;

while( j>=i && k>=i && (c=p.charAt(k)) != '*') {
if( c!='?' && c!=s.charAt(j) ) return false;
--j;
--k;
}

if(i>j)return false;
else s=s.substring(i,j+1);
if(i>k) return false;
else p=p.substring(i,k+1);

String[] pattern = p.split("[*]");
for(String temp:pattern){
if(temp.length()>0){
int index = getFirstIndex(s,temp);
if(index<0)
return false;
else
s=s.substring(index+temp.length());
}
}
return true;
}

public int getFirstIndex(String s, String p){
if(s.length()<p.length()) return -1;
int i=0;
while(i<=s.length()-p.length()){
while(i<s.length() && p.charAt(0)!='?' && p.charAt(0)!=s.charAt(i))
i++;
if(s.length()-i<p.length()) return -1;

int j=i;
while(j-i<p.length() && (p.charAt(j-i)=='?'||p.charAt(j-i)==s.charAt(j)))
j++;
if(j-i==p.length()) return i;
i++;
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: