enh(CPlusPlus): balanced-parenthesis (#380)

pull/386/head
Ujjwal 2021-07-09 18:57:24 +05:30 committed by GitHub
parent 85086f2465
commit 2dc6f8ea0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 49 additions and 37 deletions

View File

@ -1,43 +1,55 @@
/*
Program to check whether the Parenthesis are balanced or not
*/
#include<bits/stdc++.h> #include<bits/stdc++.h>
using namespace std; using namespace std;
bool isBalanced(string s) { bool isBalanced(string s) {
stack<char> st; stack < char > st;
char ch; char data;
for (int i = 0; i < s.length(); i++) { int i;
if (s[i] == '(' || s[i] == '[' || s[i] == '{') { /*
st.push(s[i]); Logic
continue; 1. Create a stack of char data type,i of int type and data of char type
} 2. Run a loop till i is less than size
if (st.empty()) 3. Assign x[i]th index value in data
return false; 4. If stack is not empty as well st.top()+2 ==(int) data (we will assume that st.top '[' or '}' so by adding two in it should
switch (s[i]) { be ']' pr '}' ) or st.top+1 (we will assume that st.top be '(' so +1 would be ')')
case ')': 5. If the 4 step didn't run then push data in it
ch = st.top(); 6. Run the step 4 and 5 till the i is less than x size
st.pop(); 7. If stack is empty that means the expression is balanced so return 1
if (ch == '{' || ch == '[') 8. If the 7 step didn't run then return 0 means the expression is not balanced
return false; */
break; for (i = 0; i < s.size(); i++) {
case '}': data = s[i];
ch = st.top(); if ((st.empty() != 1) && ((int)(st.top() + 2) == (int) data || (int)(st.top() + 1) == (int) data))
st.pop(); st.pop();
if (ch == '(' || ch == '[') else
return false; st.push(data);
break; }
case ']': return (st.empty());
ch = st.top();
st.pop();
if (ch == '(' || ch == '{')
return false;
break;
}
}
return (st.empty());
} }
int main() { int main() {
string input = "{}[({})]"; int t;
if (isBalanced(input)) string a;
cout << "Balanced"; cout << "Enter the number of test cases ";
else cin >> t;
cout << "Not Balanced"; // run loop till t is not equal to 0
return 0; while (t--) {
cout << "Enter the expression ";
cin >> a;
if (isBalanced(a))
cout << "Expression " << a << " is balanced" << endl;
else
cout << "Expression " << a << " is not balanced" << endl;
}
} }
/*
Input: Enter the number of test cases: 1
Enter the expression: ([{}])
Output:
Expression ([{}]) is balanced
Time Complexity: O(| x |);
Space Complexity: O(| x |);
*/