您的位置:首页 > 其它

Leetcode: Generalized Abbreviation

2016-01-01 01:07 162 查看
Write a function to generate the generalized abbreviations of a word.

Example:
Given word = "word", return the following list (order does not matter):
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]


这道题肯定是DFS/Backtracking, 但是怎么DFS不好想,跟Leetcode: Remove Invalid Parentheses的backtracking很像。

Generalized Abbreviation这道题是当前这个字母要不要abbreviate,要或者不要两种选择,Parentheses那道题是当前括号要不要keep在StringBuffer里,要或不要同样是两种选择。

Syntax:注意27行使用StringBuffer.setLength(), 因为count一直累加可能变成两位数三位数,delete stringbuffer最后一个字母可能不行,所以干脆设置为最初进recursion的长度

参考了:https://leetcode.com/discuss/76783/easiest-14ms-java-solution-beats-100%25

public class Solution {
public List<String> generateAbbreviations(String word) {
List<String> res = new ArrayList<String>();
dfs(0, word.toCharArray(), new StringBuffer(), 0, res);
return res;
}

public void dfs(int pos, char[] word, StringBuffer sb, int count, List<String> res) {
int len = word.length;
int sbOriginSize = sb.length();
if (pos == len) {
if (count > 0) {
sb.append(count);
}
res.add(sb.toString());
}
else {
//choose to abbr word[pos]
dfs(pos+1, word, sb, count+1, res);

//choose not to abbr word[pos]
//first append previous count to sb if count>0
if (count > 0) sb.append(count);
sb.append(word[pos]);
dfs(pos+1, word, sb, 0, res);
}
sb.setLength(sbOriginSize);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: