Skip to content

Latest commit

 

History

History
82 lines (71 loc) · 2.03 KB

20.-valid-parentheses.md

File metadata and controls

82 lines (71 loc) · 2.03 KB

20. Valid Parentheses

  • Easy

  • Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

Solution Python

class Solution:
    def isValid(self, s: str) -> bool:
        openb={"(":")","{":"}","[":"]"}
        ans=[]
        for i in s:
            if i in openb:
                ans.append(i)
            else:
                if ans==[]:
                    return False
                check=ans.pop()
                if openb[check]!=i:
                    return False
        return ans == []

Solution C

Notice that in the program we are using '' instead of "". In C they mean differently: Double quotes for strings and single quotes for characters.

bool isValid(char * s){
    int n = strlen(s);
    char* test=malloc(sizeof(char)*n);
    char c,e;
    int top=0;
    for (int i=0;i<n;i++){
        c=s[i];
        if (c==')'){
            if (top==0){
                return false;
            } 
            top-=1;
            e=test[top];
            if (e!='('){
                return false;
            }
        }else if (c==']'){
            if (top==0){
                return false;
            } 
            top-=1;
            e=test[top];
            if (e!='['){
                return false;
            }
        }else if (c=='}'){
            if (top==0){
                return false;
            } 
            top-=1;
            e=test[top];
            if (e!='{'){
                return false;
            }
        }else{
            test[top]=c;
            top+=1;
        }
    }
    return (top==0);
}