有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成
  • typedef char	STDatatype;
    struct stack
    {
    	STDatatype* arr; 
    	int top;
    	int capacity;
    };
    typedef struct stack ST;
    
    void STInit(ST* ps);//初始化
    void STDestory(ST* ps);//销毁
    void STPush(ST* ps, STDatatype x);//压栈
    void STPop(ST* ps);//出栈;
    STDatatype STTop(ST* ps);//栈顶的数
    int STSize(ST* ps);//栈的大小
    bool STEmpty(ST* ps);
    void STInit(ST* ps)
    {
    	assert(ps);
    	ps->arr = NULL;
    	ps->top = 0;
    	ps->capacity = 0;
    
    }
    
    void STDestory(ST* ps)
    {
    	assert(ps);
    	free(ps->arr);
    	ps->arr = NULL;
    	ps->top = 0;
    	ps->capacity = 0;
    }
    void STPush(ST* ps, STDatatype x)
    {
    	assert(ps);
    	//满了扩容
    	if (ps->top == ps->capacity)
    	 {
    		int newcapacity;
    		if (ps->capacity == 0)
    		{                                                   
    			newcapacity = 4;
    		}
    		else 
    		{
    
    			 newcapacity = 2 * ps->capacity;
    			
    		}
    		STDatatype* temp = (STDatatype*)realloc(ps->arr, newcapacity * sizeof(STDatatype));
    		if (temp == NULL)
    		{
    			perror("realloc fail!");
    			return;
    		}
    		ps->arr = temp;
    		ps->capacity = newcapacity;
    	}
    
     	ps->arr[ps->top] = x;
    	ps->top++;
    	
    	
    }
    void STPop(ST* ps)
    {
    	assert(ps);
    	ps->top--;
    }
    STDatatype STTop(ST* ps)
    {
    	assert(ps);
    	assert(!STEmpty(ps));
    	return ps->arr[ps->top - 1];
    }
    int STSize(ST* ps)
    {
    	assert(ps);
    	return ps->top;
    }
    bool STEmpty(ST* ps)
    {
    	assert(ps);
    	return ps->top == 0;
    }
    
    bool isValid(char* s) {
        ST st;
        STInit(&st);
        while(*s)
        {
            if(*s=='(' || *s=='[' || *s=='{')
            {
                STPush(&st,*s);
            }
            else
            {
                if(STEmpty(&st))
                {
                    return false;
                }
                char top=STTop(&st);
                STPop(&st);
                if((*s==')' && top!='(') 
                ||(*s==']' && top!='[')
                ||(*s=='}' && top!='{')
                )
                {
                    return false;
                }
            }
            
        
            s++;
        }
    
    
    
        bool ret=STEmpty(&st);
        STDestory(&st);
        
        return ret;
    }

  • 16
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值