Basic Recursion, Check Balanced Parenthesis

前端 未结 12 1238
孤独总比滥情好
孤独总比滥情好 2020-11-29 17:56

I\'ve written software in the past that uses a stack to check for balanced equations, but now I\'m asked to write a similar algorithm recursively to check for properly neste

12条回答
  •  死守一世寂寞
    2020-11-29 18:14

    The idea is to keep a list of the opened brackets, and if you find a closing brackt, check if it closes the last opened:

    • If those brackets match, then remove the last opened from the list of openedBrackets and continue to check recursively on the rest of the string
    • Else you have found a brackets that close a nerver opened once, so it is not balanced.

    When the string is finally empty, if the list of brackes is empty too (so all the brackes has been closed) return true, else false

    ALGORITHM (in Java):

    public static boolean isBalanced(final String str1, final LinkedList openedBrackets, final Map closeToOpen) {
        if ((str1 == null) || str1.isEmpty()) {
            return openedBrackets.isEmpty();
        } else if (closeToOpen.containsValue(str1.charAt(0))) {
            openedBrackets.add(str1.charAt(0));
            return isBalanced(str1.substring(1), openedBrackets, closeToOpen);
        } else if (closeToOpen.containsKey(str1.charAt(0))) {
            if (openedBrackets.getLast() == closeToOpen.get(str1.charAt(0))) {
                openedBrackets.removeLast();
                return isBalanced(str1.substring(1), openedBrackets, closeToOpen);
            } else {
                return false;
            }
        } else {
            return isBalanced(str1.substring(1), openedBrackets, closeToOpen);
        }
    }
    

    TEST:

    public static void main(final String[] args) {
        final Map closeToOpen = new HashMap();
        closeToOpen.put('}', '{');
        closeToOpen.put(']', '[');
        closeToOpen.put(')', '(');
        closeToOpen.put('>', '<');
    
        final String[] testSet = new String[] { "abcdefksdhgs", "[{aaadd}]<232>", "[ff{", "{<}>" };
        for (final String test : testSet) {
            System.out.println(test + "  ->  " + isBalanced(test, new LinkedList(), closeToOpen));
        }
    }
    

    OUTPUT:

    abcdefksdhgs  ->  true
    [{aaadd}]<232>  ->  true
    [ff{  ->  false
    {<}>  ->  false
    

    Note that i have imported the following classes:

    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Map;
    

提交回复
热议问题