From 074e3c87322741b20271c43cdbee657105010602 Mon Sep 17 00:00:00 2001 From: Vilas Sonje <109056349+SonjeVilas@users.noreply.github.com> Date: Thu, 31 Oct 2024 11:56:48 +0530 Subject: [PATCH] Remove_Invalid_Parenthesis.py --- backtracking/Remove_Invalid_Parenthesis.py | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 backtracking/Remove_Invalid_Parenthesis.py diff --git a/backtracking/Remove_Invalid_Parenthesis.py b/backtracking/Remove_Invalid_Parenthesis.py new file mode 100644 index 000000000..8b5a29dc9 --- /dev/null +++ b/backtracking/Remove_Invalid_Parenthesis.py @@ -0,0 +1,50 @@ +def isParenthesis(c): + return ((c == '(') or (c == ')')) + +def isValidString(str): + cnt = 0 + for i in range(len(str)): + if (str[i] == '('): + cnt += 1 + elif (str[i] == ')'): + cnt -= 1 + if (cnt < 0): + return False + return (cnt == 0) + +# method to remove invalid parenthesis +def removeInvalidParenthesis(str): + if (len(str) == 0): + return + + visit = set() + + q = [] + temp = 0 + level = 0 + + q.append(str) + visit.add(str) + while(len(q)): + str = q[0] + q.pop(0) + if (isValidString(str)): + print(str) + + level = True + if (level): + continue + for i in range(len(str)): + if (not isParenthesis(str[i])): + continue + + temp = str[0:i] + str[i + 1:] + if temp not in visit: + q.append(temp) + visit.add(temp) + +expression = "()())()" +removeInvalidParenthesis(expression) +expression = "()v)" +removeInvalidParenthesis(expression) +