unable to correctly validate balanced parenthesis parsing in java method

前端 未结 2 931
-上瘾入骨i
-上瘾入骨i 2021-01-29 01:47

I have a method that\'s supposed to validate accurate opening and closing parenthesis in a string using java. This method will be used to parse mathematical expressions so it\'s

相关标签:
2条回答
  • 2021-01-29 02:24

    As far as I can tell, there is no problem with the code (turns out it's a Java 7 specific issue..).

    I would like to offer a replacement method though, for educational purposes, that is shorter, and and is tolerant of other characters being present:

    public static boolean parChecker(String str) {
        Stack stack = new Stack(str.length());
        for (char c : str.toCharArray())
            switch (c) {
            case '(':
                stack.push(c);
                break;
            case ')':
                if (stack.isEmpty() || stack.pop() != Character.valueOf('('))
                    return false;
            }
        return stack.isEmpty();
    }
    

    As requested, here's another solution that doesn't use a stack:

    public static boolean parChecker(String str) {
        str = str.replaceAll("[^()]", "");
        while (str.contains("()"))
            str = str.replace("()", "");
        return str.isEmpty();
    }
    

    And one more for the road: @FredK's algorithm:

    public static boolean parChecker(String str) {
        int depth = 0;
        for ( char c : str.toCharArray() )      
            if ( ( depth += c == '(' ? 1 : c == ')' ? -1 : 0 ) < 0 )
                return false;
        return depth == 0;
    }
    
    0 讨论(0)
  • 2021-01-29 02:34

    The immediate problem is this

    String[] tokens = str.split("");
    

    Gives you first char = "" if you use java 1.7 or less, so you will exit your loop since stack is empty...

    Note: this has been changed in java 1.8 split difference between java 1.7 and 1.8

    change to:

    char[] tokens = str.toCharArray();
    

    I guess however that you need to consider the fact that there can be chars before your first ( and that you may have other chars then ( and )

    0 讨论(0)
提交回复
热议问题