fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <list>
  4. #include <algorithm>
  5. #include <iterator>
  6.  
  7. using namespace std;
  8.  
  9. list<string> bracesExpressionExamples = {
  10. "({[{}]{}[]})",
  11. "({}}{[{}]{}[]})",
  12. "({[{}]{}[]}",
  13. "({[{}]{}]})",
  14. "({[{}{}[]})",
  15. "",
  16. "{}"
  17. };
  18.  
  19. bool is_balanced(std::string s) {
  20. int counts[3] = {0};
  21. for (char ch : s) {
  22. switch (ch) {
  23. case '(': counts[0]++; break;
  24. case ')': counts[0]--; break;
  25. case '[': counts[1]++; break;
  26. case ']': counts[1]--; break;
  27. case '{': counts[2]++; break;
  28. case '}': counts[2]--; break;
  29. default: break;
  30. }
  31. }
  32. return counts[0] + counts[1] + counts[2] == 0;
  33. }
  34.  
  35. int main(int, char**) {
  36. cout << boolalpha;
  37. transform(bracesExpressionExamples.begin(),
  38. bracesExpressionExamples.end(),
  39. ostream_iterator<bool>(cout, "\n"),
  40. is_balanced);
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
true
false
false
false
false
true
true