/** * @param{string} s * @return{boolean} */varisValid=function (s) {let valid =true;conststack= [];constmapper= {"{":"}","[":"]","(":")", };for (let i in s) {constv= s[i];if (["(","[","{"].indexOf(v) >-1) {stack.push(v); } else {constpeak=stack.pop();if (v !== mapper[peak]) {returnfalse; } } }if (stack.length>0) returnfalse;return valid;};
Python Code:
classSolution:defisValid(self,s): stack = []map={"{":"}","[":"]","(":")"}for x in s:if x inmap: stack.append(map[x])else:iflen(stack)!=0: top_element = stack.pop()if x != top_element:returnFalseelse:continueelse:returnFalsereturnlen(stack)==0
classSolution:defisValid(self,s):while'[]'in s or'()'in s or'{}'in s: s = s.replace('[]','').replace('()','').replace('{}','')returnnotlen(s)
JavaScript:
varisValid=function (s) {while (s.includes("[]") ||s.includes("()") ||s.includes("{}")) { s =s.replace("[]","").replace("()","").replace("{}",""); } s =s.replace("[]","").replace("()","").replace("{}","");returns.length===0;};