Skip to content

Instantly share code, notes, and snippets.

@Dimanaux
Last active August 17, 2017 18:04
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 Dimanaux/16497feb40e4e3302d9d0e5c9ef800b1 to your computer and use it in GitHub Desktop.
Save Dimanaux/16497feb40e4e3302d9d0e5c9ef800b1 to your computer and use it in GitHub Desktop.
function validBraces checks if string contains valid sequence of braces
#include <string>
// #include <algorithm>
// #include <iostream>
#include <vector>
#include <map>
#include <stack>
// #pragma once
#ifndef BRACES_H
#define BRACES_H
bool validBracesSequence(const std::string&);
// gets any string with braces
bool validBraces(const std::string& someString) {
// checks if character is a bracket
auto isBrace = [](char c) {
for (const auto& b : "()[]{}<>") {
if (c == b) {
return true;
}
}
return false;
};
std::string braces;
// copying only braces from string
for (const auto& sym : someString) {
if (isBrace(sym)) {
braces += sym;
}
}
return validBracesSequence(braces);
}
// STRING MUST CONTAIN ONLY SYMBOLS (){}[]<>
bool validBracesSequence(const std::string& braces) {
const std::map<char, char> pairs = {
{'(', ')'},
{'[', ']'},
{'{', '}'},
{'<', '>'}
};
// keys for map pairs
const std::vector<char> leftBraces = { '(', '[', '{', '<' };
std::stack<char> seq;
for (const auto& c : braces) {
if (count(leftBraces.begin(), leftBraces.end(), c)) {
seq.push(pairs[c]);
} else if (c == seq.top()) {
seq.pop();
}
else if (seq.empty() || c != seq.top()) {
return false;
}
}
// after all stack must be empty
return seq.empty();
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment