leetcode Generalized Abbreviation
2016-07-20 19:32
337 查看
Write a function to generate the generalized abbreviations of a word.
Example:
Given word =
Show Company Tags
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
Discuss Pick
One
主要说一下递归思路,自己之前写的感觉不是很正确,网上看到比较正确的思路是这样的,用一个变量count来表示当前连续的缩写个数,那么当遇到一个新的char时,只有两种选择:1、继续缩写,count+1 2、不缩写,输出当前count,输出该字符,重置count为0,代码:
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"]
Show Company Tags
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
Discuss Pick
One
主要说一下递归思路,自己之前写的感觉不是很正确,网上看到比较正确的思路是这样的,用一个变量count来表示当前连续的缩写个数,那么当遇到一个新的char时,只有两种选择:1、继续缩写,count+1 2、不缩写,输出当前count,输出该字符,重置count为0,代码:
public List<String> generateAbbreviations(String word) { List<String> list=new ArrayList<>(); search(word.toCharArray(),list,new StringBuffer(),0,0); return list; } public void search(char[] word,List<String> list,StringBuffer str,int count,int len){ int length=str.length(); if(len==word.length){ if(count!=0) str.append(count); list.add(str.toString()); }else{ search(word,list,str,count+1,len+1); if(count!=0){ str.append(count); } search(word,list,str.append(word[len]),0,len+1); } str.setLength(length); }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法