Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <queue>
- using std::string;
- struct Stack
- {
- std::queue<char> q1, q2;
- int curr_size;
- Stack()
- {
- curr_size = 0;
- }
- void push(char x)
- {
- q1.push(x);
- curr_size++;
- }
- void pop()
- {
- if (q1.empty())
- return;
- while (q1.size() != 1)
- {
- q2.push(q1.front());
- q1.pop();
- }
- q1.pop();
- curr_size--;
- std::queue<char> q = q1;
- q1 = q2;
- q2 = q;
- }
- int top()
- {
- if (q1.empty())
- return -1;
- while (q1.size() != 1) {
- q2.push(q1.front());
- q1.pop();
- }
- char temp = q1.front();
- q1.pop();
- q2.push(temp);
- std::queue<char> q;
- q = q1;
- q1 = q2;
- q2 = q;
- return temp;
- }
- int size()
- {
- return curr_size;
- }
- bool empty()
- {
- return curr_size == 0;
- }
- };
- bool isValid(string s)
- {
- Stack st;
- for (char c : s)
- {
- if (st.empty())
- {
- if (c == '(' || c == '[' || c == '{')
- {
- st.push(c);
- }
- else
- {
- return false;
- }
- }
- else
- {
- if (c == '(')
- {
- if (st.top() == '(')
- {
- return false;
- }
- else
- {
- st.push(c);
- }
- }
- else if (c == ')')
- {
- if (st.top() != '(')
- {
- return false;
- }
- else
- {
- st.pop();
- }
- }
- else if (c == '[')
- {
- if (st.top() == '(' || st.top() == '[')
- {
- return false;
- }
- else
- {
- st.push(c);
- }
- }
- else if (c == ']')
- {
- if (st.top() != '[')
- {
- return false;
- }
- else
- {
- st.pop();
- }
- }
- else if (c == '{')
- {
- if (st.top() == '(' || st.top() == '[' || st.top() == '{')
- {
- return false;
- }
- else
- {
- st.push(c);
- }
- }
- else if (c == '}')
- {
- if (st.top() != '{')
- {
- return false;
- }
- else
- {
- st.pop();
- }
- }
- }
- }
- if(st.empty())
- return true;
- else return false;
- }
- int main()
- {
- string s;
- std::cin >> s;
- if (isValid(s))
- {
- std::cout << "Expresia este valida.\n";
- }
- else
- {
- std::cout << "Expresia nu este valida.\n";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment