Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <map>
  4. #include <stack>
  5. #include <string>
  6.  
  7. const char EOL('\n');
  8. const std::map<std::string, std::string> BRACKET = {
  9. { "(", ")" },
  10. { "[", "]" },
  11. { "{", "}" },
  12. { "<", ">" },
  13. { "(*", "*)" }
  14. };
  15.  
  16. bool is_begin_bracket(const std::string & data, int & bracket_size)
  17. {
  18. if (BRACKET.find(data) != BRACKET.end())
  19. {
  20. bracket_size = 2;
  21. return true;
  22. }
  23.  
  24. if (BRACKET.find(data.substr(0, 1)) != BRACKET.end())
  25. {
  26. bracket_size = 1;
  27. return true;
  28. }
  29.  
  30. return false;
  31. }
  32.  
  33. bool is_end_bracket(const std::string & data, int & bracket_size)
  34. {
  35. for (auto & iter : BRACKET)
  36. {
  37. if (iter.second == data)
  38. {
  39. bracket_size = 2;
  40. return true;
  41. }
  42. else if (iter.second == data.substr(0, 1))
  43. {
  44. bracket_size = 1;
  45. return true;
  46. }
  47. }
  48.  
  49. return false;
  50. }
  51.  
  52. bool validate(const std::string & line_with_eol, int & fail_index)
  53. {
  54. std::stack<std::string> bracket_stack;
  55. int pos = 0;
  56. for (size_t i = 0; i < line_with_eol.length() - 1; ++i)
  57. {
  58. std::string checking_data = line_with_eol.substr(i, 2);
  59. int bracket_size = 0;
  60. if (is_begin_bracket(checking_data, bracket_size))
  61. {
  62. bracket_stack.push((bracket_size != 1) ? checking_data : checking_data.substr(0, 1));
  63. }
  64. else if (is_end_bracket(checking_data, bracket_size))
  65. {
  66. std::string end_bracket = (bracket_size != 1) ? checking_data : checking_data.substr(0, 1);
  67. if (bracket_stack.empty() ||
  68. BRACKET.find(bracket_stack.top())->second != end_bracket)
  69. {
  70. fail_index = pos + 1;
  71. return false;
  72. }
  73.  
  74. bracket_stack.pop();
  75. }
  76.  
  77. if (bracket_size == 2)
  78. {
  79. ++i;
  80. }
  81.  
  82. ++pos;
  83. }
  84.  
  85. if (!bracket_stack.empty())
  86. {
  87. fail_index = pos + 1;
  88. return false;
  89. }
  90.  
  91. return true;
  92. }
  93.  
  94. int main()
  95. {
  96. std::ifstream input("input.txt");
  97. std::ofstream output("output.txt");
  98.  
  99. std::string line;
  100. while (std::getline(input, line, EOL))
  101. {
  102. int fail_index = 0;
  103. if (validate(line + EOL, fail_index))
  104. {
  105. output << "YES" << EOL;
  106. }
  107. else
  108. {
  109. output << "NO " << fail_index << EOL;
  110. }
  111. }
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement