1. 程式人生 > >[C語言][LeetCode][20]Valid Parentheses

[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; }