codewars--js--Valid Braces--正则、键值数组

时间:2022-08-02 12:06:34

问题描述:

Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

Examples

"(){}[]"   =>  True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False

我的答案:

 function validBraces(braces){
//TODO
var str=braces.split("");
var stack=[];
var RegExp=/[\(\{\[]/;
for(var i=0;i<str.length;i++){
if(str[i].match(RegExp)){
stack.push(str[i]);
}else{
switch (str[i]){
case ")":
if(stack.pop()!=="("){return false;}break;
case "}":
if(stack.pop()!=="{"){return false;} break;
case "]":
if(stack.pop()!=="["){return false;}break;
}
}
} if(stack.length==0){return true;}
else{return false;}
}

优秀答案:

 function validBraces(braces){
while(/\(\)|\[\]|\{\}/g.test(braces)){braces = braces.replace(/\(\)|\[\]|\{\}/g,"")}
return !braces.length;
}
 function validBraces(braces){
var matches = { '(':')', '{':'}', '[':']' };
var stack = [];
var currentChar; for (var i=0; i<braces.length; i++) {
currentChar = braces[i]; if (matches[currentChar]) { // opening braces
stack.push(currentChar);
} else { // closing braces
if (currentChar !== matches[stack.pop()]) {
return false;
}
}
} return stack.length === 0; // any unclosed braces left?
}

本题很自然就想到了使用栈的方法。但是对于使用键值数组,想到该方法,但是不会使用。另外对于replace("()","")这种巧妙的方法确实没有想到。