Leetcode-20.有效的括号(C语言)两种方法

题目描述

给定一个只包括 '('')''{''}''['']' 的字符串 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值