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.
这一题是典型的使用压栈的方式解决的问题,题目中还有一种valid情况没有说明,需要我们自己考虑的,就是"({[]})"这种层层嵌套但可以完全匹配的,也是valid的一种。
解题思路:(5个case)
1:我们对字符串S中的每一个字符C,如果C是左括号,就压入栈stack中。
2:如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid
3:如果C是右括号, 并且 stack不为空,但是 左括号与 右括号不匹配 则直接返回not vaild
4:如果是匹配的,就弹出栈顶的字符,继续取S中的下一个字符;
5: 当我们遍历了一次字符串S后,注意这里还有一种情况,就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,因为只要valid,一定全都可以得到匹配使左括号弹出。
// // ValidParentheses.c // Algorithms // // Created by TTc on 15/6/17. // Copyright (c) 2015年 TTc. All rights reserved. // /** * 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. */ #include "ValidParentheses.h" #include <stdlib.h> #include <stdbool.h> #include <string.h> bool isValid(char* s) { char *a; int top; //top of stack size_t n = strlen(s); a = (char*)malloc(sizeof(char*) * (n+1)); top = -1; int i; for( i = 0 ; i< n ; i++ ){ if (s[i]=='{' || s[i]== '[' || s[i] == '(') a[++top]=s[i]; else if (top==-1 && (s[i]=='}' || s[i]== ']' || s[i] == ')')) return 0; else if ( (s[i]==')'&& a[top]!='(') || (s[i]=='}'&& a[top]!='{') ||(s[i]==']'&&a[top]!='[') ) return 0; else if( (s[i]==')'&& a[top]=='(') || (s[i]=='}'&& a[top]=='{') || (s[i]==']'&& a[top]=='[') ) top--; } if(top == -1) return 1; else return 0; } void test_isValid(){ char *ss = "(1222,rrr(3))"; bool result = isValid(ss); printf("result ==%d",result); }