fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using std::cout;
  5. using std::endl;
  6. using std::string;
  7.  
  8. struct Node {
  9. char data;
  10. Node* next;
  11. };
  12. Node* top = nullptr;
  13.  
  14. void push(char a) {
  15. Node* temp = new Node;
  16. temp->data = a;
  17. temp->next = top;
  18. top = temp;
  19. }
  20.  
  21. void pop() {
  22. if (top != nullptr) {
  23. Node* temp = top;
  24. top = top->next;
  25. delete temp;
  26. }
  27. }
  28.  
  29. void Print(){
  30. Node *temp = top;
  31. while(temp!=nullptr){
  32. cout<<temp->data<<endl;
  33. temp=temp->next;
  34. }
  35. }
  36.  
  37. class Solution {
  38. public:
  39. bool isValid(string s) {
  40. for (char c : s) {
  41. if (c == '(' || c == '{' || c == '[') {
  42. push(c);
  43. Print();
  44. } else {
  45. if (top == nullptr) return false;
  46. char topchar = top->data;
  47. if ((c == ')' && topchar == '(') || (c == '}' && topchar == '{') || (c == ']' && topchar == '[')) {
  48. Print();
  49. pop();
  50.  
  51. } else {
  52. return false;
  53. }
  54. }
  55. }
  56. return top == nullptr;
  57. }
  58. };
  59.  
  60. int main()
  61. {
  62. Solution s;
  63.  
  64. std::cout << s.isValid("{[]}");
  65.  
  66. }
Success #stdin #stdout 0.01s 5288KB
stdin
{[]}
stdout
{
[
{
[
{
{
1