Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 12, 2017 22:40
Show Gist options
  • Save shailrshah/463f4732db3a2d7ab844a15187645b8a to your computer and use it in GitHub Desktop.
Save shailrshah/463f4732db3a2d7ab844a15187645b8a to your computer and use it in GitHub Desktop.
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).
private static String getClean(String pattern){
StringBuilder sb = new StringBuilder();
sb.append(pattern.charAt(0));
for(int i = 1; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
if(ch != '*') sb.append(ch);
else {
char lastChar = sb.charAt(sb.length()-1);
if(lastChar!='*') sb.append(ch);
}
}
return sb.toString();
}
// isMatch("x?y*z", "xaybcz") -> true
// 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
// dp[i][j] = isMatch considering s.substring(0, i) and p.substring(0, j)
public boolean isMatch(String s, String p) {
if(p.length() == 1 && p.charAt(0) == '*') return true;
if(s.length() == 0 && p.length() == 0)
return true;
if(s.length() == 0 || p.length() == 0)
return false;
p = getClean(p);
char[] str = s.toCharArray();
char[] pat = p.toCharArray();
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
if(pat[0] == '*')
dp[0][1] = true;
dp[0][0] = true;
for(int i = 1; i < dp.length; i++) {
for(int j = 1; j < dp[0].length; j++) {
if(pat[j-1] == str[i-1] || pat[j-1] == '?')
dp[i][j] = dp[i-1][j-1];
else if (pat[j-1] == '*')
dp[i][j] = dp[i][j-1] || dp[i-1][j];
}
}
return dp[s.length()][p.length()];
}
@ArashPartow
Copy link

A detailed explanation of wildcard pattern matching and general globbing can be found here:

https://www.partow.net/programming/wildcardmatching/index.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment