fork download
  1. #include <vector>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. static const std::vector<std::string> EXAMPLES = {
  6. "({[{}]{}[]})",
  7. "({}}{[{}]{}[]})",
  8. "({[{}]{}[]}",
  9. "({[{}]{}]})",
  10. "({[{}{}[]})",
  11. "",
  12. "{}",
  13. "(i (am so [lispish]))",
  14. };
  15.  
  16. static const char eof = char(-1);
  17. static const std::string open_braces = "({[";
  18. static const std::string close_braces = ")}]";
  19.  
  20. inline char matching_brace(char c)
  21. {
  22. const std::size_t i = close_braces.find(c);
  23. return i != std::string::npos ? open_braces[i] : eof;
  24. }
  25.  
  26. static bool is_balanced(const std::string &s)
  27. {
  28. std::string brace_stack;
  29.  
  30. for (auto c : s) {
  31. if (open_braces.find(c) != std::string::npos) {
  32. brace_stack.push_back(c);
  33. continue;
  34. }
  35.  
  36. const char pair = matching_brace(c);
  37. if (pair != eof) {
  38. if (!brace_stack.empty() && brace_stack.back() == pair) {
  39. brace_stack.pop_back();
  40. } else {
  41. return false;
  42. }
  43. }
  44. }
  45.  
  46. return brace_stack.empty();
  47. }
  48.  
  49. int main()
  50. {
  51. std::cout << std::boolalpha;
  52. for (const auto & e : EXAMPLES) {
  53. std::cout << is_balanced(e) << "\n";
  54. }
  55. return 0;
  56. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
true
false
false
false
false
true
true
true