我正在解决一个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
}
我不明白为什么代码不适用于这个特定的测试用例.
我错在哪里?