leetcode-有效的括号(三种语言不同思路)

C语言 

bool isValid(char * s){
    int length = strlen(s);
    //因为设置的str空间是从下标1开始的,所以要length/2+2
    //用length/2是因为括号都是配对的,用一半的就行了
    char* str=(char*)malloc(length/2+2);
    memset(str,0,length/2+2);//初始化内存空间
    int i,j=0;
    for(i=0;i

C++ 利用栈进行判断

class Solution {
public:
    bool isValid(string s) {
        stackst;
        if(s.size()%2==1)
           return false;                       //奇数个括号,直接返回false
        for(int i=0;i

python

class Solution:
    def isValid(self, s: str) -> bool:
        //如果括号是奇数,肯定是错误的
        if len(s)%2 != 0:
            return False
        while '()' in s or '[]' in s or '{}' in s:
            s = s.replace('[]','').replace('()','').replace('{}','')
        return True if s == '' else False

 

你可能感兴趣的:(LeetCode,c++,stack,数据结构,算法)