Leetcode: Generalized Abbreviation


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

 1 public class Solution {
 2     public List<String> generateAbbreviations(String word) {
 3         List<String> res = new ArrayList<String>();
 4         dfs(0, word.toCharArray(), new StringBuffer(), 0, res);
 5         return res;
 6     }
 7     
 8     public void dfs(int pos, char[] word, StringBuffer sb, int count, List<String> res) {
 9         int len = word.length;
10         int sbOriginSize = sb.length();
11         if (pos == len) {
12             if (count > 0) {
13                 sb.append(count);
14             }
15             res.add(sb.toString());
16         }
17         else {
18             //choose to abbr word[pos]
19             dfs(pos+1, word, sb, count+1, res);
20             
21             //choose not to abbr word[pos]
22             //first append previous count to sb if count>0
23             if (count > 0) sb.append(count);
24             sb.append(word[pos]);
25             dfs(pos+1, word, sb, 0, res);
26         }
27         sb.setLength(sbOriginSize);
28     }
29 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM