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

题目

有效括号序列_牛客题霸_牛客网 (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 分钟前
【初探数据结构】时间复杂度和空间复杂度
数据结构·算法
a_j582 分钟前
算法与数据结构(环形链表II)
数据结构·算法·链表
冷琴19969 分钟前
基于python+django的宠物商店-宠物管理系统源码+运行步骤
python·django·宠物
Reese_Cool11 分钟前
【爬虫】request库
爬虫·python
愚戏师21 分钟前
从零到一学习c++(基础篇--筑基期十一-类)
开发语言·数据结构·c++·学习·算法
thinkMoreAndDoMore42 分钟前
python与C系列语言的差异总结(2)
java·c语言·python
郑祎亦1 小时前
Java String 类
java·开发语言·python
小仙有礼了1 小时前
ArcGis for js 4.x实现测量,测距,高程的功能
javascript·算法·arcgis
轩源源1 小时前
unordered_set和unordered_map的使用
开发语言·数据结构·c++·算法·哈希算法·unordered_map·unordered_set
geekmice1 小时前
bat命令在b站下载单个音视频
python·音视频