Leetcode parantheses question basically need to balance the parantheses
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
But for the test case “{[]}” I am getting output as false even tho in my IDE i am getting output as true.
struct Node {
char data;
Node* next;
};
Node* top = nullptr;
void push(char a) {
Node* temp = new Node;
temp->data = a;
temp->next = top;
top = temp;
}
void pop() {
if (top != nullptr) {
Node* temp = top;
top = top->next;
delete temp;
}
}
void Print(){
Node *temp = top;
while(temp!=NULL){
cout<<temp->data<<endl;
temp=temp->next;
}
}
class Solution {
public:
bool isValid(string s) {
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
push(c);
Print();
} else {
if (top == nullptr) return false;
char topchar = top->data;
if ((c == ')' && topchar == '(') || (c == '}' && topchar == '{') || (c == ']' && topchar == '[')) {
Print();
pop();
} else {
return false;
}
}
}
return top == nullptr;
}
};
In this image you can clearly see extra ‘(‘ braces in stdout which are not given in input
I want to know if the problem is with my logic, or something wrong with testcase because in my ide its working fine
5
Here we have a textbook example of the dangers of global variables. When a test case fails, you will have crap leftover in your linked list, and you don’t clear out the list for each new test case. Running that test by itself works. Running that test after a failure fails.
You could just set top = nullptr;
at the top of the function, but that will leak all the nodes from the failed test. Perhaps you should clear the list before exiting.
4