我正在解决一个LeetCode问题20. Valid Parentheses:

给定一个字符串s只包含字符'('')''{''}''['']',确定输入字符串是否有效.

输入字符串在以下情况下有效:

  • 左方括号必须用相同类型的方括号结束.
  • 开括号必须以正确的顺序合上.
  • 每个闭括号都有一个相应的同类型的开括号.

已经通过了许多测试 case .它只是失败了一百

我的意见:https://leetcode.com/problems/valid-parentheses/submissions/1202908225/

我的代码

typedef struct node
{
    char data;
    struct node *next;
} node;

node *head = NULL;

int isEmpty(node *head)
{
    return head == NULL;
}

node *pop(node *head)
{
    node *temp = head;
    head = head->next;
    free(temp);
    return head;
}

node *push(node *head, char a)
{
    if (head == NULL)
    {
        head = (node *)malloc(sizeof(node));
        head->data = a;
        head->next = NULL;
        return head;
    }
    else
    {
        node *temp = (node *)malloc(sizeof(node));
        temp->data = a;
        temp->next = head;
        return temp;
    }
}

char peek(node *head)
{
    return head->data;
}

bool isValid(char *s)
{
    int len = strlen(s);

    for (int i = 0; i < len; i++)
    {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[')
        {
            head = push(head, s[i]);
        }
        else
        {
            if (isEmpty(head)) // Check if stack is empty
            {
                return false;
            }
            else if ((s[i] == ')' && peek(head) == '(') ||
                     (s[i] == '}' && peek(head) == '{') ||
                     (s[i] == ']' && peek(head) == '['))
            {
                head = pop(head);
            }
            else
            {
                return false;
            }
        }
    }

    return isEmpty(head); // Check if stack is empty after processing all characters
}

我不明白为什么代码不适用于这个特定的测试用例.

我错在哪里?

推荐答案

问题是你没有在函数返回之前清理你的链表,而且下次调用isValid函数时,前一个链表仍然存在,而且可能不是空的,这会影响下一次调用的结果.

为了解决这个问题,不应该将head定义为全局变量,而应该定义为isValid的局部变量,并且通过释放仍然分配给列表中 node 的内存来避免内存泄漏.

因此,为了将代码的更改保持在最低限度,我们可以这样做:

// Add this function for removing all nodes from a list
node* clear(node *head) {
    while (head) {
        head = pop(head);
    }
    return NULL;
}

bool isValid(char *s)
{
    node *head = NULL; // Local variable!
    int len = strlen(s);

    for (int i = 0; i < len; i++)
    {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[')
        {
            head = push(head, s[i]);
        }
        else
        {
            if (isEmpty(head)) 
            {
                return false;
            }
            else if ((s[i] == ')' && peek(head) == '(') ||
                     (s[i] == '}' && peek(head) == '{') ||
                     (s[i] == ']' && peek(head) == '['))
            {
                head = pop(head);
            }
            else
            {
                head = clear(head); // Avoid leaking memory
                return false;
            }
        }
    }
    bool result = isEmpty(head);
    head = clear(head); // Avoid leaking memory
    return result; 
}

C++相关问答推荐

什么C代码将确定打开的套接字正在使用的网络适配器?

从内联程序集调用Rust函数和调用约定

将 typewriter LF打印到Windows终端,而不是隐含的CR+LF

在C中将通用字符名称转换为UTF-8

我无法让LLDB正确运行我的可执行文件

使用C时,Windows CMD中的argc参数是否包含重定向命令?

使用双指针动态分配和初始化2D数组

如何在C中使printf不刷新标准输出?

在为hashmap创建加载器时,我的存储桶指向它自己

使用错误的命令执行程序

从uint8_t*转换为char*可接受

在创建动态泛型数组时,通过realloc对故障进行分段

每次除以或乘以整数都会得到0.0000

为什么我从CSV文件中进行排序和搜索的代码没有显示数据的所有结果?

为什么未初始化的 struct 的数组从另一个数组获取值?

Wcstok导致分段故障

链表删除 node 错误

C: NULL>;NULL总是false?

与指针的原始C数组或C++向量<;向量<;双>>;

Makefile - 将 .o 文件放入子文件夹中