problem:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
example:
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Difficulty:Easy
hint:
- 使用一个栈存储左括号,碰到输入的字符为右括号时则出栈,并比较两个括号是否匹配。
- 所有字符比较完成后,栈应为空,表示所有括号都相对应。
code:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
//typedef int bool;
//#define true 1
//#define false 0
typedef enum {true=1, false=0} bool;
bool isValid(char* s){
char* t = (char*)malloc(strlen(s)*sizeof(char));
int i,j = 0;
for(i = 0;i<strlen(s);i++){
switch(s[i]){ //接受新的字符
case '(':
t[j++] = ')';
break;
case '{':
t[j++] = '}';
break;
case '[':
t[j++] = ']';
break;
default:
if(t[--j]!=s[i]){ //出栈并比较两个字符
return false;
}
break;
}
}
if(j!=0){
return false;
}
return true;
}
int main(){
bool f = isValid("(");
printf("%d",f);
}