[C语言][LeetCode][20]Valid Parentheses
2016-12-09 10:58
323 查看
题目
Valid ParenthesesGiven 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; }
相关文章推荐
- LeetCode_Easy心得:20. Valid Parentheses(C语言)
- [LeetCode 20] Valid Parentheses Solution
- leetcode20-Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode 20] 20 Valid Parentheses
- [C++]LeetCode 20: Valid Parentheses(判断运算符有效性)
- LeetCode 20 — Valid Parentheses(C++ Java Python)
- LeetCode --- 20. Valid Parentheses
- 20. Valid Parentheses Leetcode Python
- [leetcode 20] Valid Parentheses
- Leetcode_20_Valid Parentheses
- LeetCode 20: Valid Parentheses
- [leetcode] 20 Valid Parentheses
- leetcode 20 Valid Parentheses
- LeetCode 20. Valid Parentheses
- [LeetCode]20 Valid Parentheses
- [Leetcode 20, Easy] Valid Parentheses
- leetcode-20 Valid Parentheses
- 【leetcode】20—valid parentheses
- [Leetcode] 20. Valid Parentheses