Task: Find the given Parenthesis string is balanced on not.
Example:
Input:
1
{[()]}
Output:
balanced
Here is the Code:
Program in C++:
- #include <iostream>
- #include <bits/stdc++.h>
- using namespace std;
- string parenthesChecker(string s)
- {
- stack<char> st;
- if(s[0]==')'||s[0]==']'||s[0]=='}')
- {
- return "not balanced";
- }
- for(int i=0;i<s.length();i++)
- {
- if(s[i]=='('||s[i]=='['||s[i]=='{')
- {
- st.push(s[i]);
- }
- else
- {
- if(st.empty()==false)
- {
- if((s[i]==')'&&st.top()=='(')||(s[i]==']'&&st.top()=='[')||(s[i]=='}'&&st.top()=='{'))
- {
- st.pop();
- }
- else
- {
- break;
- }
- }
- }
- }
- if(st.empty())
- {
- return "balanced";
- }
- else
- {
- return "not balanced";
- }
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- string s;
- cin>>s;
- cout<<parenthesChecker(s)<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment