Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active November 22, 2023 19:46
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 juanfal/31d162639fd43cd40efead6fd5decf3e to your computer and use it in GitHub Desktop.
Save juanfal/31d162639fd43cd40efead6fd5decf3e to your computer and use it in GitHub Desktop.
are braces balanced
// t11e19.validbraces.cpp
// juanfc 2023-11-22
//
#include <iostream>
using namespace std;
const string OPENING = "([{<“‘";
const string CLOSING = ")]}>”’";
void test(string s);
int main()
{
test( "(){}[]" );
test( "(}" );
test( "[(])" );
test( "([{}])" );
return 0;
}
bool validBraces(string s);
void test(string s)
{
if (validBraces(s))
cout << '"' << s << "\": has braces balanced" << endl;
else
cout << '"' << s << "\": has NOT braces balanced" << endl;
}
int find(string s, char c);
bool validBraces(string s)
{
string stack;
int i = 0;
bool balanced = true;
while (i < s.length() and balanced) {
int posPair = find(OPENING, s[i]);
if (posPair >= 0)
stack += OPENING[posPair];
else {
posPair = find(CLOSING, s[i]);
if (posPair >= 0) {
// is the last opening the partner or this closing?
int prev = find(OPENING, stack[stack.length()-1]);
balanced = prev == posPair;
if (balanced)
stack = stack.substr(0, stack.length()-1);
}
}
++i;
}
return stack == "";
}
int find(string s, char c)
{
int i = 0;
while (i < s.length() and s[i] != c)
++i;
return (i < s.length())? i: -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment