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

题目

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、String

难度

简单

分析

题目意思是给定一个字符串,仅包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’,确定字符串是否有效。

实现思路是利用栈,遍历字符串,如果遇到’(‘, ‘{‘, ‘[‘,则入栈 ,如果遇到’)’, ‘}’, ‘]’,则比较栈顶元素,如果是对应的字符,则出栈,否则返回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));

    //memcpy(&node->Element, ele, sizeof(ElemType));
    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;
}

你可能感兴趣的:(算法)