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

题目

有效括号序列_牛客题霸_牛客网 (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;
}
相关推荐
会的全对٩(ˊᗜˋ*)و9 分钟前
【数据挖掘】数据挖掘综合案例—银行精准营销
人工智能·经验分享·python·数据挖掘
??tobenewyorker18 分钟前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
___波子 Pro Max.28 分钟前
GitHub Actions配置python flake8和black
python·black·flake8
贾全40 分钟前
第十章:HIL-SERL 真实机器人训练实战
人工智能·深度学习·算法·机器学习·机器人
GIS小天1 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年7月4日第128弹
人工智能·算法·机器学习·彩票
满分观察网友z1 小时前
开发者的“右”眼:一个树问题如何拯救我的UI设计(199. 二叉树的右视图)
算法
阿蒙Amon1 小时前
【Python小工具】使用 OpenCV 获取视频时长的详细指南
python·opencv·音视频
橘子编程2 小时前
Python-Word文档、PPT、PDF以及Pillow处理图像详解
开发语言·python
蓝婷儿2 小时前
Python 机器学习核心入门与实战进阶 Day 2 - KNN(K-近邻算法)分类实战与调参
python·机器学习·近邻算法
森焱森3 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机