
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Minimum Invalid Parenthesis to Make String Correct in Python
Suppose we have a string of parentheses; we have to write a function to compute the minimum number of parentheses to be removed to make the string correct (each open parenthesis is eventually closed).
So, if the input is like "(()))(", then the output will be 2, as the correct string is "(())", remove ")(".
To solve this, we will follow these steps −
- total := 0, temp := 0
- for each p in s, do
- if p is same as "(", then
- total := total + 1
- otherwise when p is same as ")" and total is not 0, then
- total := total - 1
- otherwise,
- temp := temp + 1
- if p is same as "(", then
- return total + temp
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): total = 0 temp = 0 for p in s: if p == "(": total += 1 elif p == ")" and total: total -= 1 else: temp += 1 return total + temp ob1 = Solution() string = "(()))(" print(ob1.solve(string))
Input
"(()))("
Output
2
Advertisements