添加 0020.有效的括号.md C语言版本

This commit is contained in:
Guanzhong Pan
2021-11-25 11:59:19 +00:00
parent e6f059f545
commit 52750d3a17

View File

@ -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;
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>