Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- #include <map>
- #include <stack>
- #include <string>
- const char EOL('\n');
- const std::map<std::string, std::string> BRACKET = {
- { "(", ")" },
- { "[", "]" },
- { "{", "}" },
- { "<", ">" },
- { "(*", "*)" }
- };
- bool is_begin_bracket(const std::string & data, int & bracket_size)
- {
- if (BRACKET.find(data) != BRACKET.end())
- {
- bracket_size = 2;
- return true;
- }
- if (BRACKET.find(data.substr(0, 1)) != BRACKET.end())
- {
- bracket_size = 1;
- return true;
- }
- return false;
- }
- bool is_end_bracket(const std::string & data, int & bracket_size)
- {
- for (auto & iter : BRACKET)
- {
- if (iter.second == data)
- {
- bracket_size = 2;
- return true;
- }
- else if (iter.second == data.substr(0, 1))
- {
- bracket_size = 1;
- return true;
- }
- }
- return false;
- }
- bool validate(const std::string & line_with_eol, int & fail_index)
- {
- std::stack<std::string> bracket_stack;
- int pos = 0;
- for (size_t i = 0; i < line_with_eol.length() - 1; ++i)
- {
- std::string checking_data = line_with_eol.substr(i, 2);
- int bracket_size = 0;
- if (is_begin_bracket(checking_data, bracket_size))
- {
- bracket_stack.push((bracket_size != 1) ? checking_data : checking_data.substr(0, 1));
- }
- else if (is_end_bracket(checking_data, bracket_size))
- {
- std::string end_bracket = (bracket_size != 1) ? checking_data : checking_data.substr(0, 1);
- if (bracket_stack.empty() ||
- BRACKET.find(bracket_stack.top())->second != end_bracket)
- {
- fail_index = pos + 1;
- return false;
- }
- bracket_stack.pop();
- }
- if (bracket_size == 2)
- {
- ++i;
- }
- ++pos;
- }
- if (!bracket_stack.empty())
- {
- fail_index = pos + 1;
- return false;
- }
- return true;
- }
- int main()
- {
- std::ifstream input("input.txt");
- std::ofstream output("output.txt");
- std::string line;
- while (std::getline(input, line, EOL))
- {
- int fail_index = 0;
- if (validate(line + EOL, fail_index))
- {
- output << "YES" << EOL;
- }
- else
- {
- output << "NO " << fail_index << EOL;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement