
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Valid Parentheses in C++
Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid.
The task is simple; we will use the stack to do this. We should follow these steps to get the solution −
Traverse through the expression until it has exhausted
if the current character is opening bracket like (, { or [, then push into stack
if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced.
After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced.
Example
#include <iostream> #include <stack> using namespace std; bool isBalancedExp(string exp) { stack<char> stk; char x; for (int i=0; i<exp.length(); i++) { if (exp[i]=='('||exp[i]=='['||exp[i]=='{') { stk.push(exp[i]); continue; } if (stk.empty()) return false; switch (exp[i]) { case ')': x = stk.top(); stk.pop(); if (x=='{' || x=='[') return false; break; case '}': x = stk.top(); stk.pop(); if (x=='(' || x=='[') return false; break; case ']': x = stk.top(); stk.pop(); if (x =='(' || x == '{') return false; break; } } return (stk.empty()); } int main() { string expresion = "()[(){()}]"; if (isBalancedExp(expresion)) cout << "This is Balanced Expression"; else cout << "This is Not Balanced Expression"; }
Input
"()[(){()}]"
Output
This is Balanced Expression
- Related Articles
- Minimum Remove to Make Valid Parentheses in C++
- Longest Valid Parentheses in Python
- Finding the longest valid parentheses JavaScript
- Minimum Add to Make Parentheses Valid in Python
- Minimum number of Parentheses to be added to make it valid in C++
- Maximum Nesting Depth of Two Valid Parentheses Strings in Python
- Program to find minimum remove required to make valid parentheses in Python
- Score of Parentheses in C++
- Remove Invalid Parentheses in C++
- Count pairs of parentheses sequences such that parentheses are balanced in C++
- Valid Sudoku in C++
- Cost to Balance the parentheses in C++
- Different Ways to Add Parentheses in C++
- Valid Parenthesis String in C++
- Valid Palindrome III in C++
