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"]思路:backtracking,从0开始替换,从1开始替换,注意两点。
1. list必须把原来的string加进去。
2. 再进行下一次循环的时候,是基于已经变换好的string,然后往下传,然后start index应该是新生成的的string的i+num.length()+1,因为要隔一个才能生成新的number。
public class Solution {
public List<String> generateAbbreviations(String word) {
List<String> list = new ArrayList<String>();
if(word == null) return list;
list.add(word);
collect(word, 0, list);
return list;
}
public void collect(String s, int start, List<String> list){
if(start >= s.length()){
return;
}
for(int i=start; i<s.length(); i++){
for(int j=1; i+j<=s.length(); j++){
String num = String.valueOf(j);
String abbv = s.substring(0,i) + num +s.substring(i+j);
list.add(abbv);
collect(abbv, i+1+num.length(), list);
}
}
}
}