Word Pattern II
Last updated
Last updated
public class Solution {
/**
* @param pattern: a string,denote pattern string
* @param str: a string, denote matching string
* @return: a boolean
*/
public boolean wordPatternMatch(String p, String s) {
// write your code here
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
return helper(p, s, map, set);
}
private boolean helper(String p, String s,
Map<Character, String> map,
Set<String> set) {
if (p.length() == 0) {
return s.length() == 0;
}
char c = p.charAt(0);
if (map.containsKey(c)) {
if (!s.startsWith(map.get(c))) {
return false;
}
return helper(p.substring(1),
s.substring(map.get(c).length()),
map, set);
} else {
for (int i = 0; i < s.length(); i++) {
String word = s.substring(0, i + 1);
if (set.contains(word)) {
continue;
}
map.put(c, word);
set.add(word);
if (helper(p.substring(1),
s.substring(i + 1),
map, set)) {
return true;
}
set.remove(word);
map.remove(c);
}
}
return false;
}
}