每日一道算法题 有效括号序列

题目

有效括号序列_牛客题霸_牛客网 (nowcoder.com)

Python

1长度必须为偶数

2就像开心消消乐一样,一左一右就消掉。

class Solution:
    def isValid(self , s: str) -> bool:
        # write code here
        # flag=['()','{}','[]']
        # for _ in range(len(s)//2):
        #     for i in flag:
        #         if i in s:
        #             s=s.replace(i,'')
        # # print(s)
        # if  len(s)==0:
        #     return True
        # else:
        #     return False
        if len(s)%2==1:
            return False
        while '()' in s or '{}' in s or '[]' in s:
            s=s.replace('()','').replace('{}','').replace('[]','')

        return True if s=='' else False

C++

使用栈,遇到左括号,右括号进栈,遇到其他则取栈顶进行匹配

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s) 
    {
        // write code here
        int n=s.size();
        if(n%2==1) return false;
        stack<char> sta;
        for(int _ =0;_<n;_++)
        {
            if(s[_]=='(') sta.push(')');
            else if(s[_]=='{') sta.push('}');
            else if(s[_]=='[') sta.push(']');
            else
            {
                if(sta.empty()||sta.top()!=s[_])
                    return false;
                sta.pop();
            }
        }
        return sta.empty();
    }
};

C语言

思路同c++

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return bool布尔型
 */
#include <string.h>
bool isValid(char* s ) 
{
    // write code here
    int l=strlen(s);
    if(l%2==1) return 0;
    char *stack=(char* )malloc(l*sizeof(char));
    int top=0;
    for(int _ =0;_<l;_++)
    {
        if(s[_]=='(') stack[top++]=')';
        else if(s[_]=='{') stack[top++]='}';
        else if(s[_]=='[') stack[top++]=']';
        else
         {
            if(top<1) return 0;
            if(stack[top-1]==s[_]) stack[--top]='\0';   //理解为c++处的pop
         };
    }
    if(strlen(stack)>0) return 0;
    return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值