Reduce string by removing outermost parenthesis from each primitive substring | Function to remove the outermost parentheses of every primitive substring from the given string ; Stores the resultant string ; Stores the count of opened parentheses ; Traverse the string ; If opening parenthesis is encountered and their count exceeds 0 ; Include the character ; If closing parenthesis is encountered and their count is less than count of opening parentheses ; Include the character ; Return the resultant string ; Driver Code
def removeOuterParentheses ( S ) : NEW_LINE INDENT res = " " NEW_LINE count = 0 NEW_LINE for c in S : NEW_LINE INDENT if ( c == ' ( ' and count > 0 ) : NEW_LINE INDENT res += c NEW_LINE DEDENT if ( c == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( c == ' ) ' and count > 1 ) : NEW_LINE INDENT res += c NEW_LINE DEDENT if ( c == ' ) ' ) : NEW_LINE count -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ( ( ) ( ) ) ( ( ) ) ( ) " NEW_LINE print ( removeOuterParentheses ( S ) ) NEW_LINE DEDENT