您的位置:首页 > 编程语言 > C语言/C++

[C语言][LeetCode][20]Valid Parentheses

2016-05-06 08:36 429 查看

题目

Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

标签

Stack、Array

难度

简单

分析

题目的意思是判断字符串里的括号是否有效。实现思路是,将( [ { 这三种符号入栈,如果遇到) ] }这三种符号,则比较栈顶符号是否匹配,如果不匹配,则返回false,如果匹配,将栈顶符号弹出,继续下一个符号比较。

C代码实现

typedef char ElemType;

typedef struct STACK_T
{
ElemType value;
struct STACK_T * next;
}STACK;

typedef struct STACK_T NODE;

STACK * stack = NULL;

STACK * stack_init(void)
{
STACK * stack = (STACK *)malloc(sizeof(STACK));
if(!stack)
{
printf("malloc stack fail\n");
return NULL;
}

memset(stack, 0, sizeof(STACK));
stack->next = NULL;

return stack;
}

bool stack_is_empty(STACK * stack)
{
return (stack->next == NULL);
}

ElemType stack_pop(STACK * stack)
{
ElemType retValue;

STACK * temp = NULL;

if(!stack_is_empty(stack))
{
temp = stack->next;
stack->next = stack->next->next;
retValue = temp->value;
free(temp);
}
else
{
printf("stack is empty\n");
return 0;
}

return retValue;
}

int stack_push(STACK * stack, ElemType ele)
{
NODE * node = (NODE *)malloc(sizeof(NODE));

node->value = ele;
node->next = stack->next;
stack->next = node;

return 0;
}

ElemType stack_top(STACK * stack)
{
if(!stack_is_empty(stack))
{
return stack->next->value;
}

return (ElemType)(-1);
}

bool isValid(char* s)
{
char * p = s;

if(!p)
return false;

if(*(p+1) == '\0')
return false;

stack = stack_init();

while(*p != '\0')
{
if( (*p == '(') ||(*p == '{') || (*p == '[') )
stack_push(stack, *p);
else if(*p == ')')
{
if('(' != stack_top(stack))
return false;
else
stack_pop(stack);
}
else if(*p == '}')
{
if('{' != stack_top(stack))
return false;
else
stack_pop(stack);
}
else if(*p == ']')
{
if('[' != stack_top(stack))
return false;
else
stack_pop(stack);
}
else
return false;

p = p + 1;
}

if(true == stack_is_empty(stack))
return true;
else
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 leetcode