检查java中的有效括号

时间:2018-05-21 15:25:28

标签: java algorithm math recursion parentheses

我试图找出给定的输入是否是有效的括号。输入字符串由'(',')',' {','}',' ['和']' 。
输入字符串在以下情况下有效:

1.打开支架必须用相同类型的支架关闭 2.必须以正确的顺序关闭打开括号。 3.空字符串有效

但是我在下面使用递归的代码不适用于有效的情况。假设转到基本情况(当输入是"")而是转到for循环后的return语句。

class Solution {

    public boolean validParen(String input) {

        if(input.isEmpty()) {
            return true;
        }

        else {
            for (int i = 0; i < input.length() - 1; i++) {
                if ((input.charAt(i) == '(' && input.charAt(i + 1) == ')') ||
                        (input.charAt(i) == '{' && input.charAt(i + 1) == '}') ||
                        (input.charAt(i) == '[' && input.charAt(i + 1) == ']')) {
                    input = input.substring(0, i) + input.substring(i + 2);
                    System.out.println("Input is " + input);
                    validParen(input);
                }
            }
            return false;
        }
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        //System.out.println(sol.validParen("")); 
        //System.out.println(sol.validParen("()")); // returns false for some reason 
        //System.out.println(sol.validParen("()[]{}")); // returns false for some reason
        //System.out.println(sol.validParen("(]"));
        //System.out.println(sol.validParen("([)]"));
        //System.out.println(sol.validParen("{[]}")); // returns false for some reason
    }
}

6 个答案:

答案 0 :(得分:1)

你试过替换

吗?
validParen(input);

return validParen(input);

? 否则这一行并没有太大作用;)

从通话顺序的角度来看,如果您从a()或其他任何地方调用方法a(),则无关紧要。 我们来看一个简单的例子

public int getOne() {
   return 1;
}

public int getA(int a) {
   /*
   what you do here is call getOne(). The method will be called,
   and it will produce some result, but this result will not be persisted
   in any way, you will just go to the next line where the original a's
   value will be returned
    */
   getOne(); 
   return a;


}

这种情况有点清楚吗?显然,如果您致电getA(2),则会返回2,而不是1,即使内部调用getOne() - 也会忽略该结果。

答案 1 :(得分:1)

如评论中所述,您可以考虑使用堆栈。当前字符为{[)时,请将它们放入堆栈中。当前字符为}]import java.util.Stack; class Solution { public boolean validParen(String input) { if (input.isEmpty()) { return true; } else { Stack<Character> stack = new Stack<>(); for (int i = 0; i < input.length(); i++) { char current = input.charAt(i); if (current == '(' || current == '[' || current == '{') { stack.push(current); } else { if(stack.isEmpty()) { return false; } char peekChar = stack.peek(); if ((current == ')' && peekChar != '(') || (current == '}' && peekChar != '{') || (current == ']' && peekChar != '[')) { return false; // for a valid input, a close brackets must have an open brackets } else { stack.pop(); } } } return true; } } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.validParen("")); System.out.println(sol.validParen("()")); System.out.println(sol.validParen("()[]{}")); System.out.println(sol.validParen("(]")); System.out.println(sol.validParen("([)]")); System.out.println(sol.validParen("{[]}")); } } 时,请检查堆栈中是否存在对应项(对于有效输入,它必须存在)并弹出它。

conn = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver', ['jdbc:oracle:thin:@hostname:1521:orcl', "username", "password"],"C:\\Users\\user\\Documents\\Drivers\\ojdbc6.jar")

答案 2 :(得分:0)

这是一个使用递归的解决方案。它直接使用调用堆栈来跟踪到目前为止已解析的括号,因此它不需要任何显式的堆栈数据结构:

import java.util.LinkedList;

class RecursiveCheckParens {

    public static int _checkParens(String input, int startIdx) {
        if (startIdx == input.length()) {
          return startIdx;
        } else {
          char c = input.charAt(startIdx);
          if ("]})".indexOf(c) >= 0) {
            return startIdx;
          } else {
            int i = _checkParens(input, startIdx + 1);
            if (i == -1) {
              return -1; // propagate failure sentinel
            } else if (i == input.length()) {
              return -1; // missing matching parenthesis
            } else {
              char cOp = input.charAt(i);
              if (
                c == '(' && cOp == ')' ||
                c == '[' && cOp == ']' ||
                c == '{' && cOp == '}'
              ) {
                return _checkParens(input, i + 1);
              } else {
                return -1;
              }
            }
          }
        }
    }

    public static boolean checkParens(String input) {
      return _checkParens(input, 0) == input.length();
    }

    public static void main(String[] args) {
      for (String example: new String[] {
        "",
        "()",
        "()[]{}",
        "(]",
        "([)]",
        "{[]}",
        "(([{}[]])([{}()]))",
        "({[()}])([])"
      }) {
        System.out.println(example + " -> " + checkParens(example)); 
      }
    }
}

输出:

 -> true
() -> true
()[]{} -> true
(] -> false
([)] -> false
{[]} -> true
(([{}[]])([{}()])) -> true
({[()}])([]) -> false
([([([])])]) -> true
([([([)]])]) -> false

请注意,该解决方案不是尾递归的。因此,它不能以消除调用堆栈的方式重写。这就是为什么它可以在调用堆栈上存储无限量的信息(也就是说,直到你内存不足并获得StackOverflow,当然......)。

答案 3 :(得分:0)

import java.util.Stack;

公共类ValidBracesTest {

public static void main(String[] args) {

    System.out.println(isValid("( [ { } ] )".toCharArray())); // valid
    System.out.println(isValid("([{}])".toCharArray())); // valid
    System.out.println(isValid("([)]".toCharArray())); // invalid
    System.out.println(isValid("(}".toCharArray())); // invalid

}

public static boolean isValid(char[] charArray) {
    Stack<Character> container = new Stack<Character>();

    for (char c : charArray) {

        if (c == ' ') {
            continue;
        }

        if (c == '(' || c == '{' || c == '[') {
            container.push(c);
        } else if (c == ')' && container.peek() == '(' 
                || (c == '}' && container.peek() == '{')
                || (c == ']' && container.peek() == '[')) {
            container.pop();
        } else {
            return false;
        }

    }

    return container.isEmpty();
}

}

答案 4 :(得分:0)

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for(int i =0; i < s.length(); i++){
       Character currentChar = s.charAt(i);
       if (currentChar == '(' || currentChar == '{' || currentChar == '[') {
            stack.push(currentChar);
       } else if(!stack.isEmpty()){
           if (currentChar == ')' && stack.peek() == '(' 
            || (currentChar == '}' && stack.peek() == '{')
            || (currentChar == ']' && stack.peek() == '[')) {
                stack.pop();
            } else {
                return false;
            }
       } else {
            return false;
        }
    }

    return stack.isEmpty();
}

答案 5 :(得分:0)

这应该是一个优雅的版本,您可以在其中插入括号的对面并检查完整性。

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<Character>();
    for (char c : s.toCharArray()) {
        if (c == '(')
            stack.push(')');
        else if (c == '{')
            stack.push('}');
        else if (c == '[')
            stack.push(']');
        else if (stack.isEmpty() || stack.pop() != c)
            return false;
    }
    return stack.isEmpty();
}