String leetcode 20 valid parentheses

Question: char *stack = (char *) malloc(sizeof(char) * (len+1));, don't you understand why?

Topic: Valid parentheses

Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.

A valid string must satisfy: the
left parenthesis must be closed with the same type of right parenthesis.
The opening parenthesis must be closed in the correct order.
Note that an empty string can be considered a valid string.

Example 1:
Input: "()"
Output: true

Example 2:
Input: “()[]{}”
Output: true

Example 3:
Input: "(]"
Output: false

Example 4:
Input: "([)]"
Output: false

Example 5:
Input: "{[]}"
Output: true

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-parentheses

python3 solution

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)

Summary: There is no do while loop in python3, it can only be written as above.

c language solution

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;
        }
}

to sum up:

Using the idea of ​​the stack, when you encounter the right parenthesis, it pops out of the stack, and the left parenthesis is pushed into the stack.

supplement:

#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;
}

Guess you like

Origin blog.csdn.net/mogbox/article/details/112743988