mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0020.有效的括号.md C语言版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user