diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 57aa5a01..6c6f0cb7 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -283,6 +283,47 @@ var isValid = function(s) { }; ``` +C: +```C +//辅助函数:判断栈顶元素与输入的括号是否为一对。若不是,则返回False +int notMatch(char par, char* stack, int stackTop) { + switch(par) { + case ']': + return stack[stackTop - 1] != '['; + case ')': + return stack[stackTop - 1] != '('; + case '}': + return stack[stackTop - 1] != '{'; + } + return 0; +} + +bool isValid(char * s){ + int strLen = strlen(s); + //开辟栈空间 + char stack[5000]; + int stackTop = 0; + + //遍历字符串 + int i; + for(i = 0; i < strLen; i++) { + //取出当前下标所对应字符 + char tempChar = s[i]; + //若当前字符为左括号,则入栈 + if(tempChar == '(' || tempChar == '[' || tempChar == '{') + stack[stackTop++] = tempChar; + //若当前字符为右括号,且栈中无元素或右括号与栈顶元素不符,返回False + else if(stackTop == 0 || notMatch(tempChar, stack, stackTop)) + return 0; + //当前字符与栈顶元素为一对括号,将栈顶元素出栈 + else + stackTop--; + } + //若栈中有元素,返回False。若没有元素(stackTop为0),返回True + return !stackTop; +} +``` + -----------------------