2016-12-03 102 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写道几乎完全在他的第一个例子同样的事情,所以没必要推倒重来!