Java 递归检查字符串是否平衡

Java 递归检查字符串是否平衡,java,string,recursion,Java,String,Recursion,我想检查字符串是否有匹配的大括号、方括号或圆括号 For example: {} () [] 我可以用一堆来做。我想用递归实现它。我正在阅读一个类似问题的答案,答案是递归混合的堆栈。一个用户回答说递归也是一个堆栈,所以递归方法的参数中不应该有堆栈——这对我来说很有意义 但是我有一个大问题,我向后看字符串,总是删除我检查的最后一个位置,直到字符串为空,所以我返回true。我无法想象如果在我的方法中没有一个额外的参数来保存我要查找的内容,我将如何检查特定的部分、大括号、方括号或圆括号。但我一直在想

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

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()));
}

使用递归解决此问题的最简单方法是从两个方向收缩字符串。从左到右迭代,直到看到。如果这些不匹配,则字符串不平衡,否则对这些大括号之间的字符串应用相同的算法。只从一端走要复杂得多,你必须存储一些状态


编辑:谢谢DanielFischer。实际上,从一侧(例如左侧)迭代,直到找到一个大括号(如果这个大括号没有打开一个返回值
false
)。然后从另一侧(本例中为右侧)迭代,直到找到匹配的大括号。现在,字符串将被平衡,当且仅当此大括号中包含的子字符串被平衡时,右括号中的字符串都使用递归进行平衡。

使用递归解决此问题的最简单方法是从两个方向收缩字符串。从左到右迭代,直到看到。如果这些不匹配,则字符串不平衡,否则对这些大括号之间的字符串应用相同的算法。只从一端走要复杂得多,你必须存储一些状态


编辑:谢谢DanielFischer。实际上,从一侧(例如左侧)迭代,直到找到一个大括号(如果这个大括号没有打开一个返回值
false
)。然后从另一侧(本例中为右侧)迭代,直到找到匹配的大括号。现在,当且仅当此大括号中包含的子字符串平衡时,字符串才会平衡。并且右括号中的字符串都使用递归进行平衡。

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

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 )
ps={'{':'}','(':')','[':']}
all_ps=set(['{','}','(',')','[',']']))
读取位置=0
def平衡(s,收盘价=无):
全局读取位置
读取位置
可以通过解析输入字符串来完成。这种情况下的语法是:

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 )
ps={'{':'}','(':')','[':']}
all_ps=set(['{','}','(',')','[',']']))
读取位置=0
def平衡(s,收盘价=无):
全局读取位置
读取位置
这里有一个解决方案,不替换任何内容,直接递归:

/**
 * @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 );

}
/**
*@param args
*/
公共布尔平衡(字符串s,整数开始,整数结束)
{
System.out.println(“开始:“+start+“end”+end”);
if(start==s.length())返回end==0;

如果(end这里有一个解决方案,不替换任何内容,直接递归:

/**
 * @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 );

}
/**
*@param args
*/
公共布尔平衡(字符串s,整数开始,整数结束)
{
System.out.println(“开始:“+start+“end”+end”);
if(start==s.length())返回end==0;

if(end)只是出于好奇。你想从递归而不是迭代中获得什么好处?只是出于好奇。你想从递归而不是迭代中获得什么好处?在我的理解中,
“()[]{}”
是平衡的。你的测试可能会说它不平衡。@danielpher正确。我会解决这个问题。谢谢。EDIT:非常有趣。我刚刚读了你的“EDIT”。但是,我认为解决方案会将([)]返回为正确。@CharlieK不,我认为你误解了我。你从左边迭代,找到一个
),然后从右边迭代(相同级别的递归还没有递归调用)并查找
。然后对