fork download
  1. #include <iomanip>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. bool foo(const string& context, const size_t pos) {
  9. const auto it = next(cbegin(context), pos);
  10. const auto before = accumulate(cbegin(context), it, 0, [](const auto output, const auto input) {
  11. if(input == '{') {
  12. return output + 1;
  13. }
  14. else if(input == '}' && output > 0) {
  15. return output - 1;
  16. }
  17. else {
  18. return output;
  19. }
  20. });
  21. const auto after = accumulate(it, cend(context), 0, [](const auto output, const auto input) {
  22. if(input == '{') {
  23. return output + 1;
  24. }
  25. else if(input == '}') {
  26. return output - 1;
  27. }
  28. else {
  29. return output;
  30. }
  31. });
  32.  
  33. return before + after >= 0;
  34. }
  35.  
  36. int main() {
  37. cout << boolalpha;
  38.  
  39. for(const auto& test : { ""s, "{"s, "}"s, "{}"s, "{{}}"s, "}{}"s, "{{}"s, "{}}"s, "{}{"s }) {
  40. cout << test << endl;
  41.  
  42. for(size_t i = 0; i <= test.size(); ++i) {
  43. cout << '\t' << i << ": " << foo(test, i) << endl;
  44. }
  45. }
  46. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
	0: true
{
	0: true
	1: true
}
	0: false
	1: true
{}
	0: true
	1: true
	2: true
{{}}
	0: true
	1: true
	2: true
	3: true
	4: true
}{}
	0: false
	1: true
	2: true
	3: true
{{}
	0: true
	1: true
	2: true
	3: true
{}}
	0: false
	1: false
	2: false
	3: true
{}{
	0: true
	1: true
	2: true
	3: true