字符串 leetcode 20 有效的括号

问题:char *stack = (char *) malloc(sizeof(char) * (len+1));,不是 很明白为什么?

题目:有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: “()”
输出: true

示例 2:
输入: “()[]{}”
输出: true

示例 3:
输入: “(]”
输出: false

示例 4:
输入: “([)]”
输出: false

示例 5:
输入: “{[]}”
输出: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

python3解法

class Solution:
    def isValid(self, s: str) -> bool:
        s1=s.replace("()","").replace("[]","").replace("{}","")
        # 受力扣圈友启发,感谢.
        # 如果s的长度没变,,说明替代没发生,要不替代完了,要么是false
        while(len(s1)<len(s)):
            # 更新s,否则s一直没变化.
            s=s1
            # 把s括号中的(){}[]提成空字符串
            s1=s.replace("()","").replace("[]","").replace("{}","")

        return not len(s1)

总结:python3中没有do while循环,只能如上写.

c语言解法

bool isValid(char * s){
    
    
    // if (s == NULL || s[0] == '\0') return true;
    int top=0;
    int len=0;
    int i=0;
    //算出s字符串的长度
    len=strlen(s);//求出字符串s的长度
    char *stack = (char *) malloc(sizeof(char) * (len+1));//多申请一个空间,因为字符串结尾\0还占一个字节,少了数组越界,看见大佬有的只申请1/2的思想非常棒
    for(i=0;i<len;i++){
    
    
        //如果是左边类型括号就进栈.
        if(s[i]=='['||s[i]=='('||s[i]=='{')
            stack[++top]=s[i];
        //如果是右边括号就出栈
        if(s[i]==']'){
    
    
            if(stack[top]=='[')
                top--;
            else 
                return false;
            }
        if(s[i]==')'){
    
    
            if(stack[top]=='(')
                top--;
            else 
                return false;
                }
        if(s[i]=='}'){
    
    
            if(stack[top]=='{')
                top--;
            else 
                return false;
                }        
    }
    //判断栈是不是空
    if(top!=0){
    
    
        free(stack);
        return false;
        }
    else{
    
    
        free(stack);
        return true;
        }
}

总结:

利用了栈的思想,遇到右括号就出栈,左括号就进栈

补充:

#include<stdio.h>
#include<string.h> 
int main() {
    
    
    char *s = "hehe";
    int len = strlen(s);
    printf("%d\n",len); //4
    //字符串是无符号的,运算时候会把-7看成大于的0的数
    printf("%d\n",strlen(s)-7>0); //1
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mogbox/article/details/112743988
今日推荐