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

题目

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

Python

1长度必须为偶数

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

python 复制代码
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++

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

cpp 复制代码
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++

cpp 复制代码
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @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;
}
相关推荐
大模型真好玩1 分钟前
做题王者,实战拉跨!是时候给马斯克的Grok4泼盆冷水了!(Grok 4模型详细测评报告)
人工智能·python·mcp
羊八井2 分钟前
使用 Earth2Studio 和 AI 模型进行全球天气预测:太阳辐照
pytorch·python·nvidia
向左转, 向右走ˉ12 分钟前
PyTorch随机擦除:提升模型抗遮挡能力
人工智能·pytorch·python·深度学习
马特说24 分钟前
金融时间序列机器学习训练前的数据格式验证系统设计与实现
python·机器学习·金融
Blue桃之夭夭24 分钟前
基于OpenCV的实时人脸检测系统实现指南 ——Python+Haar级联分类器从环境搭建到完整部署
人工智能·python·opencv
偷偷的卷24 分钟前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
木头左26 分钟前
决策树与随机森林Python实践
python·随机森林
北京地铁1号线31 分钟前
Zero-Shot(零样本学习),One-Shot(单样本学习),Few-Shot(少样本学习)概述
人工智能·算法·大模型
网小鱼的学习笔记41 分钟前
python中MongoDB操作实践:查询文档、批量插入文档、更新文档、删除文档
开发语言·python·mongodb
Q_Q5110082851 小时前
python的保险业务管理与数据分析系统
开发语言·spring boot·python·django·flask·node.js·php