Generalized Abbreviation
Thoughts
Code
class Solution {
private void dfs(String word, int pos, String cur, int count, List<String> res) {
if (pos == word.length()) {
if (count > 0) {
cur += count;
}
res.add(cur);
} else {
dfs(word, pos + 1, cur, count + 1, res);
dfs(word, pos + 1, cur + (count > 0 ? count : "") + word.charAt(pos), 0, res);
}
}
public List<String> generateAbbreviations(String word) {
List<String> res = new ArrayList<>();
dfs(word, 0, "", 0, res);
return res;
}
}Analysis
Last updated