【问题标题】:Recursively check if a String is balanced递归检查字符串是否平衡
【发布时间】:2013-02-02 18:05:33
【问题描述】:

我想检查一个字符串是否有匹配的大括号、方括号或圆括号。

For example:
{}
()
[]

我可以用堆栈来做到这一点。我想用递归来做。我正在阅读类似问题的答案,答案是递归与堆栈混合。一位用户回复了这些答案,说递归也是一个堆栈,因此您的递归方法不应该在参数中包含堆栈——这对我来说很有意义。

我有一个大问题,我正在向后查看字符串,并且总是删除我检查的最后一个位置,直到字符串为空,所以我返回 true。如果我的方法中没有额外的参数来保存我要查找的内容,我无法想象如何检查特定部分、大括号、方括号或括号。但我一直认为必须有一种更简单的方法来做到这一点。

public boolean isBalanced(String in)
{
    if(in.isEmpty())
        return true;

    if(in.charAt(in.length()) == '}')
    {
        return recIsBalanced(in.substring(0, in.length()));
    }

    else if(in.charAt(in.length()) == ']')
    {

    }


    return recIsBalanced(in.substring(0, in.length()));
}

【问题讨论】:

  • 只是出于好奇。您想从递归而不是迭代中获得什么好处?

标签: java string recursion


【解决方案1】:

使用递归解决此问题的最简单方法是从两个方向收缩字符串。您从左到右进行迭代,直到看到 .如果这些不匹配,则字符串不平衡,否则对括在这些大括号之间的字符串应用相同的算法。只从一端开始会更棘手,您必须存储一些状态。

编辑:感谢 DanielFischer。实际上从一侧迭代,例如离开直到你找到一个大括号(如果这个大括号没有打开一个返回false)。比从另一边迭代(在这种情况下是正确的)直到找到匹配的大括号。现在,当且仅当括号内的子字符串平衡并且右括号右侧的字符串都使用递归平衡时,字符串才会平衡。

【讨论】:

  • 在我的理解中,"()[]{}" 是平衡的。你的测试会说不是。
  • @DanielFischer 正确。我会解决的。谢谢。
  • 编辑:非常有趣。我刚刚读了你的“编辑”。但是,我认为该解决方案会将 ([ )] 返回为正确的。
  • @CharlieK 不,我想你误解了我的意思。您从左侧迭代并找到(,然后从右侧迭代(相同级别的递归还没有递归调用)并找到)然后你对()之间的子字符串和)右侧的部分进行递归调用。
  • @Ivaylo Strandjev "( 并从右边迭代(相同级别的递归还没有递归调用)并找到"。所以递归调用中的循环寻找右括号?
【解决方案2】:

可以通过解析输入字符串来完成。这种情况的语法是:

P -> (P)
P -> [P]
P -> {P}
P -> e  (Null)

在字符串中跟踪解析的内容更容易,并且递归堆栈包含要关闭的括号。这是简单的python实现。

ps = { '{': '}', '(': ')', '[': ']'}
all_ps = set(['{', '}', '(', ')', '[', ']'])
read_position = 0

def _is_balanced( s, closing_par=None ):
  global read_position
  while read_position < len(s):
    if s[read_position] == closing_par:
      read_position += 1         # Read closing parenthesis
      return True
    elif s[read_position] in ps:
      read_position += 1         # Read opening parenthesis
      if not _is_balanced( s, ps[s[read_position-1]] ):
        return False
    else:
      if s[read_position] not in all_ps:
        read_position += 1       # Read non-parenthesis char
      else:
        return False            # It is closing parenthesis, witouh opening before
  return closing_par is None    # Are we looking for a closing parenthesis?

def is_balanced( s ):
  global read_position
  read_position = 0  # Reset parsing position
  return _is_balanced( s )

【讨论】:

    【解决方案3】:
     public static boolean isBalanced(String str) {
    
        if (str.length() == 0) {
            return true;
        }
        if (str.contains("()")) {
            return isBalanced(str.replaceFirst("\\(\\)", ""));
        }
    
        if (str.contains("[]")) {
            return isBalanced(str.replaceFirst("\\[\\]", ""));
        }
    
        if (str.contains("{}")) {
            return isBalanced(str.replaceFirst("\\{\\}", ""));
        } else {
            return false;
        }
    }
    

    【讨论】:

      【解决方案4】:

      这是一个解决方案,不替换任何东西,直接递归:

      /**
       * @param args
       */
      public  boolean balance(String s, int start, int end)
      {
         System.out.println("start:"+start + " end" + end);
         if (start == s.length()) return end == 0;
         if (end<0) return false;
         //if (end == s.length()-1) return start == 0;
         if (s.charAt(start) == '(')
           return balance(s, start+1, end+1);
         if (s.charAt(start) == ')')
           return balance(s, start+1, end-1);
         return balance(s, start+1, end );
      
      }
      

      【讨论】:

        【解决方案5】:
        boolean isBalanced(String str)
        {
            if (str.isEmpty()) {
                return true;
            }
            else if (str.charAt(0) == '(') {
                return str.charAt(str.length() - 1) == ')'
                    && isBalanced(str.substring(1, str.length()));
            }
            else if (str.charAt(0) == '[') {
                return str.charAt(str.length() -  1) == ']'
                    && isBalanced(str.substring(1, str.length()));
            }
            else if (str.charAt(0) == '{') {
                return str.charAt(str.length() - 1) == '}'
                    && isBalanced(str.substring(1, str.length()));
            }
            else {
                return true;
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-19
          • 2013-12-28
          • 2013-02-03
          • 2012-09-14
          • 1970-01-01
          • 2013-02-02
          • 2018-06-23
          • 1970-01-01
          • 2011-11-04
          相关资源
          最近更新 更多