2016-12-03 46 views
4

我想如下解壓縮串看起來:遞歸串減壓

輸入:4(AB)

輸出:ABABABAB

輸入:11AB

輸出:aaaaaaaaaaab

輸入:2(3b3(ab))

輸出:bbbabababbb bababab

上述例子都出來正確使用遞歸方法以下,但出現的問題,當我輸入是這樣的:

輸入:4(AB)一個

預期輸出:ababababa

輸入:2(3B3(AB))一

預期輸出:bbbabababbbbabababa

我知道出現在哪裏第問題e返回語句「返回重複」。在當前狀態下的遞歸繼續,直到它甚至一個結束括號後碰到輸入字符串的結尾。基本上我不知道如何得到它打破,如果到達結束括號,然後繼續,如果有什麼事。在2(3B3(AB))一個它應該返回2 *(3B3(AB))+一個,現在它返回2 *(3B3(AB))一個。任何幫助非常感謝,因爲我無法得到我的頭。我注意到

public static String decompress(String compressedText) throws Exception 
{ 
    //BASE CASE 
    if(compressedText.length() == 1) 
    { 
     if(compressedText.charAt(0) == ')') 
     { 
      System.out.println("1: " + compressedText); 
      return ""; 
     } 
     else 
     { 
      System.out.println("2: " + compressedText); 
      return compressedText; 
     } 

    } 
    //END BASECASE 


    if(compressedText.charAt(0) == '(') 
    { 
     System.out.println("3: " + compressedText); 
     return decompress(compressedText.substring(1));   
    } 


    //IF DOUBLE DIGIT 
    if(Character.isDigit(compressedText.charAt(0)) == true && Character.isDigit(compressedText.charAt(1)) == true) 
    { 
     if(compressedText.charAt(3) != '(') 
     { 
      System.out.println("4: " + compressedText); 
      int i = Integer.parseInt(compressedText.substring(0,2)); 
      String repeated = new String(new char[i]).replace("\0", compressedText.substring(2,3)); 
      return repeated + decompress(compressedText.substring(3)); 
     } 
     else 
     { 
      System.out.println("5: " + compressedText); 
      int i = Integer.parseInt(compressedText.substring(0,2)); 
      String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(2))); 
      return repeated; 
     } 

    } 
    //END DOUBLE DIGIT 



    //IF SINGLE DIGIT 
    if (Character.isDigit(compressedText.charAt(0)) == true) 
    { 
     if(compressedText.charAt(1) !='(') 
     { 
      System.out.println("6: " + compressedText); 
      int i = Integer.parseInt(compressedText.substring(0,1)); 
      String repeated = new String(new char[i]).replace("\0", compressedText.substring(1,2)); 
      return repeated + decompress(compressedText.substring(2)); 
     } 
     else 
     { 
      System.out.println("7: " + compressedText); 
      int i = Integer.parseInt(compressedText.substring(0,1)); 
      String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(1))); 
      return repeated; 
     } 

    } 
    //END SINGLE DIGIT 

    //IF RIGHT PARENTHESIS 
    if (compressedText.charAt(0) == ')') 
    { 
     if (compressedText.charAt(1) != ')') 
     { 
      System.out.println("8: " + compressedText); 
      return ""; 
     } 
     else 
     { 
      System.out.println("9: " + compressedText); 
      return decompress(compressedText.substring(1)); 

     } 

    } 
    //END 

     System.out.println("10: " + compressedText); 
     return compressedText.charAt(0)+decompress(compressedText.substring(1)); 

} 
+1

'2(3b3(ab))a'的預期輸出是'bbbabababbbbabababa' –

+0

有趣的問題。你可以使用遞歸下降解析器和一個小的BNF語法。然後你可以在10分鐘內將代碼敲出來。 –

+0

好的,添加了JavaScript代碼示例。 –

回答

1

的一件事是,你是「失去」最後的「一」,當你輸出"8:"後返回""。在該位置後字符應該如何處理爲好,但你不能簡單地返回有他們 - 不直接,也沒有通過解壓縮他們 - ,因爲這會導致bbbabaabaababbbabaabaaba

不幸的是,我沒有找到一個基於你的代碼的解決方案,它返回正確的值(我猜在你如何將部分處理的文本放入遞歸中存在一些奇怪的行爲,但我不確定.. )。

但是,我想過我會如何解決這個壓縮的事情,並與兩個非遞歸解決方案上來。也許他們幫助你改進你的解決方案。注意:我的解決方案假設字符串是格式良好的,也就是說沒有任何不匹配的括號等。 (我在回答結束時使用了一個重複函數。)

第一個解決方案使用正則表達式來搜索數字和以下部分(一個字符或一個不包含括號的括號封閉的部分)。這樣,支架和單字符decompressions從內到外進行處理。

public static String decompressWithRegex(String s) { 
    if ((s == null) || (s.length() == 0)) { 
     return s; 
    } 
    // pattern for finding number with either bracket-enclosed, char-only part or single char 
    Pattern p = Pattern.compile("(\\d+)((?:[^\\d\\(\\)]{1})|(?:\\([^\\d\\(\\)]+\\)))"); 
    String tmp = s; 
    Matcher m = p.matcher(tmp); 
    // start searching 
    while (m.find(0)) { 
     // first capture group returns count 
     int count = Integer.parseInt(m.group(1)); 
     // second group is string to repeat (if it's bracket-enclosed, then remove brackets) 
     String what = m.group(2).replace("(", "").replace(")", ""); 
     // build replacement part 
     String replacePart = repeat(what, count); 
     // replace it 
     tmp = m.replaceFirst(replacePart); 
     // reset matcher (source of matcher is now the new string) 
     m.reset(tmp); 
    } 
    return tmp; 
} 

不使用正則表達式的第二個解決方案。相反,它使有關減壓如何處理一些假設:

  • 它後面沒有括號括起來的一部分的任何數量的可直接 解壓原地的,這是做第一
  • 支架-enclosed部分被找到第一個右括號處理
  • 然後從那裏回至開始左括號中搜索
  • 這可以讓你的部分重複
  • 左左括號應該有一個號碼是然後搜索了一個d解析
  • 現在我們擁有所有的信息,更換部分建成並投入在正確的地方
  • 那麼下一個右括號進行搜索,如果有任何,這是因爲上述
  • 處理,如果有是沒有閉合托架,所述字符串被減壓

代碼:

0123:

public static String decompressWithSearching(String s) { 
    if ((s == null) || (s.length() == 0)) { 
     return s; 
    } 
    // replace non-groups first 
    for (int i = s.length() - 1; i >= 0; i--) { 
     // find digit that is not followed by bracket 
     if (Character.isDigit(s.charAt(i)) && s.charAt(i + 1) != '(') { 
      // string to repeat is right behind the digit 
      String part = s.substring(i + 1, i + 2); 
      // find complete digit 
      String countStr = ""; 
      int j = i; 
      for (; j >= 0 && Character.isDigit(s.charAt(j)); j--) { 
       countStr = s.charAt(j) + countStr; 
      } 
      int count = Integer.parseInt(countStr); 
      // build replacement part 
      String replacePart = repeat(part, count); 
      // replace part 
      s = s.substring(0, j + 1) + replacePart + s.substring(i + 2); 
     } 
    } 

    // replace nested parts 
    int closing; 
    while ((closing = s.indexOf(')')) > -1) { 
     // find matching opening bracket 
     int opening = s.lastIndexOf('(', closing); 
     // text between is to be repeated 
     String what = s.substring(opening + 1,closing); 
     // find complete digit 
     String countStr = ""; 
     int numPartIndex = opening - 1; 
     while (numPartIndex >= 0 && Character.isDigit(s.charAt(numPartIndex))) { 
      countStr = s.charAt(numPartIndex) + countStr; 
      numPartIndex--; 
     } 
     int count = Integer.parseInt(countStr); 
     // build replacement part 
     String replacePart = repeat(what, count); 
     // replace part 
     s = s.substring(0, numPartIndex + 1) + replacePart + s.substring(closing + 1); 
    } 

    return s; 
} 

用於重複字符串實用方法

public static String repeat(String what, int times) { 
    if ((times <= 0) || (what == null) || (what.length() == 0)) { 
     return ""; 
    } 
    StringBuilder buffer = new StringBuilder(times * what.length()); 
    for (int i = 0; i < times; i++) { 
     buffer.append(what); 
    } 
    return buffer.toString(); 
} 
+0

不錯。我非常喜歡第一個例子。 –

1

使用元組爲遞歸的返回值,其提供了右括號的索引除了累積字符串:

index 0 1 2 3 4 5 6 7 8 9 10 
str 2 (3 b 3 (a b)) a 

    f(0) 

    => 2 * f(1)[0] add f(f(1)[1] + 1) // f(1)[1] is the closing index 

    f(1) => 3 * b + 3 * f(5)[0] add f(f(5)[1] + 1) 

    => f(5) returns (ab,8) 

    f(1) => bbb + ababab add f(9) // str[9] is closing parenthesis 

    => f(1) returns (bbbababab,9) 

    => 2 * bbbababab add f(10) 

    => bbbabababbbbabababa 

JavaScript代碼:

var example = '2(3b3(ab)2(cd3(fg)))ab2(gh2(xz))'; 
 

 
console.log(example); 
 
console.log(decompress(example)); 
 

 
function decompress(s){ 
 

 
    // returns tuple [accumulator, index of closing parenthesis] 
 
    function f(i){ 
 
    
 
    var accum = '', 
 
     mult = '', 
 
     curr = ''; 
 
     
 
    // accumulate all parenthetical groups in this level 
 
    while (i !== s.length){ 
 

 
     // closing parenthesis 
 
     if (s[i] === ')'){ 
 
     
 
     // add the last decompression 
 
     if (curr !== ''){ 
 
      accum += customReplicate(curr,mult); 
 
     } 
 
     
 
     // exit this call 
 
     return [accum,i]; 
 
     } 
 
      
 
     // character is a digit 
 
     if (!isNaN(parseInt(s[i]))){ 
 
     
 
     // add previous decompression 
 
     if (curr !== ''){ 
 
      accum += customReplicate(curr,mult); 
 
      
 
      curr = ''; 
 
      mult = s[i]; 
 
      
 
     } else { 
 
      mult += s[i]; 
 
     } 
 
     
 
     i++; 
 
     
 
     // character is a character 
 
     } else if (s[i] !== '('){ 
 
     
 
     curr += s[i]; 
 
     i++; 
 
     
 
     // parenthetical group 
 
     } else if (s[i] === '('){ 
 
     
 
     // recursive call 
 
     [tempAccum,index] = f(i + 1); 
 

 
     accum += customReplicate(tempAccum,mult); 
 
     mult = ''; 
 
     i = index + 1; 
 
     } 
 
    } 
 
    
 
    return accum + customReplicate(curr,mult); 
 
    } 
 
    
 
    // initialize the recursion 
 
    return f(0); 
 
} 
 

 
function customReplicate(str,times){ 
 
    return new Array(times === '' ? 1 : parseInt(times)) 
 
       .fill(str).join(''); 
 
}

+0

我想我理解這個邏輯,但是我的java知識不足以實際實現它。我嘗試添加一個for循環,當遇到一個數字後面跟着一個括號時,「看上去」前進。返回括號內的壓縮部分+接下來的內容。 類似於: 返回重複(直到「))」)+壓縮文本(所有後來的「))」)。這個問題是,當輸入是你在上面的代碼中使用的字符串「))」出現兩次..所以我的問題是這將如何實現?並感謝您的答案! – APL888

+1

@ APL888感謝您的評論。我不熟悉Java;讓我看看我能否寫出一個不應該太差的JavaScript版本,然後回覆你。 –

0

我意識到這是一個Java問題,但我通常會寫一個小的Ruby co de在Java中實現它之前測試一個想法。如果感興趣的人,這裏是我的代碼:

def decompress(str) 
    str.gsub!(/(\d+)([a-z])/i){$2*$1.to_i}  # Replace every subtring like "3b" and "11a". 
    while str.include?('(') do 
    str.sub!(/(\d+)\(([a-z]+)\)/){$2*$1.to_i} # Replace the first inner group found 
    end 
    str 
end 

puts decompress("4(ab)")  == "abababab" 
puts decompress("11ab")  == "aaaaaaaaaaab" 
puts decompress("2(3b3(ab))") == "bbbabababbbbababab" 
puts decompress("4(ab)a")  == "ababababa" 
puts decompress("2(3b3(ab))a") == "bbbabababbbbabababa" 
#=> true, true, true, true, true 

@jCoder寫道幾乎完全在他的第一個例子同樣的事情,所以沒必要推倒重來!