Write a function to generate the generalized abbreviations of a word.
public List<String> generateAbbreviations(String word) {
List<String> res = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
char[] arr = word.toCharArray();
dfs(res, tmp, arr, 0, 0);
return res;
}
private void dfs(List<String> res, StringBuilder tmp, char[] arr, int pos, int cnt) {
if (pos == arr.length) {
if(cnt > 0) tmp.append(cnt);
res.add(tmp.toString());
return;
}
// use number 记录tmp的长度, 在本段结束之后设置回tmp长度
int len = tmp.length();
dfs(res, tmp, arr, pos + 1, cnt + 1); 增加 pos 和 cnt, 保持 tmp 不变
tmp.setLength(len); // 回溯
// use character
int len = tmp.length();
if(cnt > 0) {
tmp.append(cnt).append(arr[pos]); 往tmp 加 cnt 和 字符
dfs(res, tmp, arr, pos + 1, 0);
} else {
tmp.append(arr[pos]); 当 cnt是 0 时, 只加 字符
dfs(res, tmp, arr, pos + 1, 0);
}
tmp.setLength(len); // backtracking
}
本文介绍了一个用于生成单词所有可能的通用缩写的算法。通过深度优先搜索(DFS)递归地构建所有可能的组合,包括全拼形式和各种数字加字母的缩略形式。
1447

被折叠的 条评论
为什么被折叠?



