This question comes from leetcode 20. valid Parentheses
1. Problem description
Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine that the input string is valid.
The brackets must be closed in the correct order, "()" and "()[]" are all valid, but "(]" and "([)]" are not.
Second, the key points of problem-solving ideas
Traverse the string, push the unmatched '(', '{', '[' to the stack, and pop the matched ones,
When the bottom of the stack is ')', '}', ']' or the stack is not empty after traversing, it returns false, otherwise it returns true
3. Algorithm code
1. Definition of stack data structure
#define MAXSIZE 10000 #define OVERFLOW 0 #define error -65530 /**Stack data structure definition**/ typedef struct Sq_stack { char data[MAXSIZE]; int top; }Sq_stack; /**Stack creation --initialization**/ void initStack(Sq_stack *S) { S = (Sq_stack*)malloc(sizeof(Sq_stack)); if(!S) exit(OVERFLOW);//Stack space allocation failed strcpy(S->data,""); S->top = 0; //The top element of the stack starts from 0 } /**Insert the top element e**/ bool Push(Sq_stack *S, char e) { /**Insert the top element of the stack: determine whether the stack is full**/ if( S->top == MAXSIZE-1 ) return false; S->top++; S->data[S->top] = e; return true; } /**Remove the top element from the stack**/ void Pop(Sq_stack *S) { /**Delete the top element of the stack: determine whether the stack is empty**/ if(S->top == 0) return; S->top--; } bool isEmptyStack( Sq_stack *S ) { return S->top == 0?true:false; }
2. Main algorithm part
/********************************************* Author:tmw date:2018-5-5 *********************************************/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> bool isValid( char *s ) { /**Algorithm entry: check s**/ if( strlen(s) == 0 ) return true; /**Apply for stack and initialize**/ Sq_stack *stk = (Sq_stack*)malloc(sizeof(Sq_stack)); initStack (pcs); /**Push rules definition**/ int i = 0; for( i=0; i<strlen(s); i++ ) { /**The current stack is empty, and the element to be pushed into the stack is the symbol element on the right, then return false directly**/ if( isEmptyStack(stk) && ( s[i]==')'||s[i]=='}'||s[i]==']') ) return false; /**Other cases -- judge the top element before pushing the stack normally**/ switch( s[i] ) { case ')': if (stk-> data [stk-> top]! = '(') return false; else Pop (pcs); break; case '}': if (stk-> data [stk-> top]! = '{') return false; else Pop (pcs); break; case ']': if (stk-> data [stk-> top]! = '[') return false; else Pop (pcs); break; default: Push(stk,s[i]); } } /**The current stack is empty, and all elements are traversed, return true directly**/ if( isEmptyStack(stk) ) return true; return false; }
4. Execution results
accept
There is still a dream, if it comes true~~~ヾ(◍°∇°◍)ノ゙~~~