zoukankan      html  css  js  c++  java
  • 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"]

    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 }
  • 相关阅读:
    如何用tar和gpg创建压缩加密的档案文件
    如何用Virt-rescue拯救虚拟机?
    如何在Linux中使用命令管理已安装的软件包?
    leetcode TOP100 字母异位词分组
    剑指offer 1-5
    XCTF(MISC) 坚持60s
    XCTF(MISC) give_you_flag
    XCTF MISC 如来十三掌
    XCTF(MISC) 图片隐写
    XCTF csaw2013reversing2
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5780288.html
Copyright © 2011-2022 走看看