Basic Recursion, Check Balanced Parenthesis

前端 未结 12 1266
孤独总比滥情好
孤独总比滥情好 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:28

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

提交回复
热议问题