LeetCode-Generalized Abbreviation

LiBlog發表於2016-08-17

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"]

Solution:
 1 public class Solution {
 2     public List<String> generateAbbreviations(String word) {
 3         List<String> res = new ArrayList<String>();
 4         StringBuilder builder = new StringBuilder();
 5 
 6         getAbbrRecur(builder,0,word,res);
 7 
 8         return res;
 9     }
10 
11     public void getAbbrRecur(StringBuilder builder, int cur, String word, List<String> res){
12         if (cur >= word.length()){            
13             // We get an abbr.
14             res.add(builder.toString());
15             return;
16         }
17         
18         // Use this to reset the builder for backtracking. Together with setLength()
19         int len = builder.length();
20         
21         // deal with not change word[cur].
22         builder.append(word.charAt(cur));
23         getAbbrRecur(builder,cur+1,word,res);
24         builder.setLength(len);
25 
26         int maxLen = word.length()-cur;
27         for (int i=1;i<=maxLen;i++){
28             // Change the following i chars into abbr number. 
29             builder.append(i);
30             // Add the next char into buffer, as it should not be changed.
31             if (cur+i < word.length()) builder.append(word.charAt(cur+i));
32             getAbbrRecur(builder,cur+i+1,word,res);
33             builder.setLength(len);
34         }
35     }
36 }