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); } }
相关文章推荐
- UILabel 的基本使用和扩展
- 栈的经典运用
- html<audio>标签实现的网页播放器
- 图像识别--翻译论文
- ARM汇编指令集
- 二零一五小结
- 黑马程序员——多线程之线程安全的实现详解
- Bye,2015;Hi,2016
- 装完Centos7提示Initial setup of CentOS Linux 7 (core)
- Hive,Hbase,HDFS等之间的关系
- Netflix学习笔记:Zuul
- OSChina App代码分析之BaseApplication
- Ubuntu SSH 开启 Root 远程登陆
- ARM指令集详解
- solutions to errors occured when compiling kernel linux-2.6.31.14
- 安装 zsh 、 on-my-zsh 和 autojump
- 2016年工作计划
- Good Bye 2015 C New Year and Domino(dp)
- 2016! 新年快乐! 猴年快乐!
- 自学Python之函数