320 Generalized Abbreviation
Write a function to generate the generalized abbreviations of a word.
Note: The order of the output does not matter.
Example:
Input: “word”
Output:
[“word”, “1ord”, “w1rd”, “wo1d”, “wor1”, “2rd”, “w2d”, “wo2”, “1o1d”, “1or1”, “w1r1”, “1o2”, “2r1”, “3d”, “w3”, “4”]
典型Backtrack+剪枝
//剪枝:已经map到某char上的string不能再拿来match
public boolean wordPatternMatch(String pattern, String str) {
return matchHelper(pattern, str, new HashMap<>(), 0, 0, new HashSet<>());
}
private boolean matchHelper(String pattern, String str,
Map<Character, String> map,
int indexP, int indexS,
Set<String> usedStrSet) {
if (indexP >= pattern.length() || indexS >= str.length()) {
return (indexP == pattern.length() && indexS == str.length());
}
char c = pattern.charAt(indexP);
if (map.containsKey(c)) {
if (indexS + map.get(c).length() > str.length()
|| !map.get(c).equals(str.substring(indexS, indexS + map.get(c).length())))
return false;
return matchHelper(pattern, str, map, indexP + 1, indexS + map.get(c).length(), usedStrSet);
} else {
//backtrack
for (int i = indexS; i < str.length() &&
i + pattern.length() - 1 - indexP < str.length(); i++) {
//string already mapped to a char, can't map to other
if (usedStrSet.contains(str.substring(indexS, i + 1)))
continue;
map.put(c, str.substring(indexS, i + 1));
usedStrSet.add(str.substring(indexS, i + 1));
if (matchHelper(pattern, str, map, indexP + 1, i + 1, usedStrSet))
return true;
map.remove(c);
usedStrSet.remove(str.substring(indexS, i + 1));
}
}
return false;
}