代码之家  ›  专栏  ›  技术社区  ›  vivekreddygiri

Leetcode有效偏旁测试用例有问题吗?

  •  -2
  • vivekreddygiri  · 技术社区  · 2 年前

    Leetcode paranthes问题基本上需要平衡paranthes 示例1:

    输入:s=“()” 输出:真

    示例2:

    输入:s=“()[]{}” 输出:真

    示例3:

    输入:s=“(]” 输出:false

    但是对于测试用例“{[]}”,即使在我的IDE中输出为true,我也会得到false的输出。

    
    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

    我想知道问题是出在我的逻辑上,还是出在测试用例上,因为在我看来,它工作得很好

    1 回复  |  直到 2 年前
        1
  •  4
  •   Tim Roberts    2 年前

    这里我们有一个关于全局变量危险的教科书示例。当一个测试用例失败时,你的链表中会有剩余的垃圾,你不会为每个新的测试用例清除列表。单独运行该测试是有效的。在失败后运行该测试失败。

    你可以设置 top = nullptr; 在函数的顶部,但这将泄漏失败测试中的所有节点。也许你应该在退出前清除列表。