Skip to content

Instantly share code, notes, and snippets.

@jlstr
Created October 15, 2013 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlstr/6992518 to your computer and use it in GitHub Desktop.
Save jlstr/6992518 to your computer and use it in GitHub Desktop.
MyCodeSchool Problem #44
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BalancedParentheses {
public:
int checkBalance(string);
};
int BalancedParentheses::checkBalance(string input) {
int counter = 0;
vector<char> vec;
for(string::size_type i = 0; i < input.size(); ++i) {
if(i == 0 && input[i] == ')')
return -1;
if(i == 0 && input[i] == '}')
return -1;
if(input[i] == '(' || input[i] == '{') {
vec.push_back(input[i]);
++counter;
} else if(input[i] == ')' || input[i] == '}') {
if(!vec.empty())
switch(input[i]) {
case ')':
if(vec[vec.size()-1] == '(') {
vec.pop_back();
--counter;
}
break;
case '}':
if(vec[vec.size()-1] == '{') {
vec.pop_back();
--counter;
}
break;
}
}
}
return counter;
}
int main() {
BalancedParentheses obj;
int cases;
string s;
cin >> cases;
for(int i = 0; i < cases; ++i) {
cin >> s;
cout << (obj.checkBalance(s) == 0 ? "YES" : "NO") << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment