Code : Balanced Parenthesis
#include <iostream>
#include <string>
using namespace std;
#include "solution.h"
int main()
{
string input;
cin >> input;
cout << ((isBalanced(input)) ? "true" : "false");
}
// #include<bits/stdc++.h>
// bool isBalanced(string expression)
// {
// // Write your code here
// Stack<int>s;
// for(int i=0;i<expression.size();i++){
// if(s.empty())s.push(expression[i]);
// else if(s.top()=='(' && expression[i]==')' ||s.top()=='{' && expression[i]=='}' || s.top()=='[' && expression[i]==']') s.pop();
// else s.push(expression[i]);
// }
// if(s.empty()) return true;
// else return false;
// }
#include <bits/stdc++.h>
bool isBalanced(string expression)
{
// Write your code here
stack<char>s;
for(int i=0; i<expression.length(); i++){
if(s.empty()){
s.push(expression[i]);
}
else if(s.top()=='(' && expression[i]==')'){
s.pop();
}
else {
s.push(expression[i]);
}
}
if(s.empty()) return true;
return false;
}
Comments
Post a Comment