mirror of https://github.com/doocs/leetcode.git
46 lines
1.2 KiB
Java
46 lines
1.2 KiB
Java
class Solution {
|
|
private Set<String> vis;
|
|
private Map<Character, String> d;
|
|
private String p;
|
|
private String s;
|
|
private int m;
|
|
private int n;
|
|
|
|
public boolean wordPatternMatch(String pattern, String s) {
|
|
vis = new HashSet<>();
|
|
d = new HashMap<>();
|
|
this.p = pattern;
|
|
this.s = s;
|
|
m = p.length();
|
|
n = s.length();
|
|
return dfs(0, 0);
|
|
}
|
|
|
|
private boolean dfs(int i, int j) {
|
|
if (i == m && j == n) {
|
|
return true;
|
|
}
|
|
if (i == m || j == n || m - i > n - j) {
|
|
return false;
|
|
}
|
|
char c = p.charAt(i);
|
|
for (int k = j + 1; k <= n; ++k) {
|
|
String t = s.substring(j, k);
|
|
if (d.getOrDefault(c, "").equals(t)) {
|
|
if (dfs(i + 1, k)) {
|
|
return true;
|
|
}
|
|
}
|
|
if (!d.containsKey(c) && !vis.contains(t)) {
|
|
d.put(c, t);
|
|
vis.add(t);
|
|
if (dfs(i + 1, k)) {
|
|
return true;
|
|
}
|
|
vis.remove(t);
|
|
d.remove(c);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
} |