题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
题目测试用例
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
个人认为的特殊情况
示例4:
输入:s="{()}[]"
输出:true
示例5:
输入:s="()}"
输出:false
示例6:
输入:s="{}("
输出:false
使用数组与栈的区别
数组不能越界,也就是不能有-1的情况
使用栈
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct
{
char a[20];
int top;
}Stack;
void InitStack(Stack *S);
_Bool Empty(Stack *S);
void Push(Stack *S,char ch,int n);
char Pop(Stack *S);
void Destory(Stack *S);
int main()
{
Stack A;
char ch[30],dh;
gets(ch);
int n=strlen(ch);
int i;
InitStack(&A);
for(i=0;i<n;i++)
{
if(ch[i]=='{'||ch[i]=='('||ch[i]=='[')
{
Push(&A,ch[i],n);
}
else if(ch[i]=='}'||ch[i]==')'||ch[i]==']')
{
if(A.top!=-1)
{
dh=Pop(&A);
if((ch[i]==')'&&dh!=ch[i]-1)||(ch[i]=='}'&&dh!=ch[i]-2)||(ch[i]==']'&&dh!=ch[i]-2))
{
printf("Not match.\n");
return 0;
}
}
else
{
printf("Not match.\n");
return 0;
}
}
}
if(Empty(&A))
{
printf("Match.\n");
}
else
printf("Not match.\n");
Destory(&A);
return 0;
}
void InitStack(Stack *S)
{
S->top=-1;
}
_Bool Empty(Stack *S)
{
if(S->top==-1)
return true;
else
return false;
}
void Push(Stack *S,char ch,int n)
{
if(S->top!=n)
{
S->a[++S->top]=ch;
}
}
char Pop(Stack *S)
{
char ch;
if(S->top!=-1)
{
ch=S->a[S->top--];
}
return ch;
}
void Destory(Stack *S)
{
S->top=-1;
}
使用数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool isValid(char * s);
int main()
{
char s[100];
gets(s);
if(isValid(s))
printf("true");
else
printf("false");
return 0;
}
bool isValid(char * s)
{
char ch[100];
strcpy(ch,s);
int n=strlen(ch);
int i=0,j=0;
char a[20],dh;
for(i=0;i<n;i++)
{
if(ch[i]=='{'||ch[i]=='('||ch[i]=='[')
{
a[j++]=ch[i];
}
else if(ch[i]=='}'||ch[i]==')'||ch[i]==']')
{
if(j!=0)
{
dh=a[--j];
if((ch[i]==')'&&dh!=ch[i]-1)||(ch[i]=='}'&&dh!=ch[i]-2)||(ch[i]==']'&&dh!=ch[i]-2))
{
return false;
}
}
else
{
return false;
}
}
}
if(j>0)
{
return false;
}
else
return true;
}