- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum number of Parentheses to be added to make it valid in C++
Problem statement
Given a string of parentheses. It can container opening parentheses ’(‘ or closing parentheses ‘)’. We have to find minimum number of parentheses to make the resulting parentheses string is valid.
Example
If str = “((()” then we required 2 closing parentheses i.e ‘))’ at end of string
Algorithm
- Count opening parentheses
- Count closing parentheses
- Required parentheses = abs(no. of opening parentheses – no. of closing parentheses)
Example
#include <iostream> #include <string> #include <cmath> using namespace std; int requiredParentheses(string str) { int openingParentheses = 0, closingParentheses = 0; for (int i = 0; i < str.length(); ++i) { if (str[i] == '(') { ++openingParentheses; } else if (str[i] == ')') { ++closingParentheses; } } return abs(openingParentheses - closingParentheses); } int main() { string str = "((()"; cout << "Required parentheses = " << requiredParentheses(str) << endl; return 0; }
When you compile and execute above program. It generates following output −
Required parentheses = 2
Advertisements