[AlgoExpert] Glob Matching

Glob Matching

  • Time : O(nm)
  • Space : O(nm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
vector<vector<int>> dp;

bool helper(string& f, string& p, int i, int j) {
if(i > f.length() or j > p.length()) return false;
if(i == f.length() and j == p.length()) return true;
if(j == p.length()) return false;
if(i == f.length()) {
for(; j < p.length(); j++) {
if(p[j] != '*') return false;
}
return true;
}
if(dp[i][j] != -1) return dp[i][j];
if(p[j] == '?') return dp[i][j] = helper(f, p, i + 1, j + 1);
else if(p[j] != '*') {
if(p[j] == f[i]) return dp[i][j] = helper(f, p, i + 1, j + 1);
return dp[i][j] = false;
}

for(int pos = i; pos <= f.length(); pos++) {
if(helper(f,p, pos, j + 1))
return dp[i][j] = true;
}

return dp[i][j] = false;
}

bool globMatching(string fileName, string pattern) {
string newPattern = "";

for(auto& ch : pattern) {
if(ch == '*') {
if(newPattern.empty() or newPattern.back() != '*')
newPattern.push_back(ch);
} else newPattern.push_back(ch);
}

int n = fileName.length(), m = newPattern.length();
dp = vector<vector<int>>(n, vector<int>(m, -1));
return helper(fileName, newPattern, 0, 0);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/glob-matching/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.