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

问题描述:

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

我的答案:

 1 function validBraces(braces){
 2   //TODO 
 3   var str=braces.split("");
 4   var stack=[];
 5   var RegExp=/[\(\{\[]/;
 6   for(var i=0;i<str.length;i++){
 7     if(str[i].match(RegExp)){
 8       stack.push(str[i]);
 9     }else{
10       switch (str[i]){
11       case ")":
12         if(stack.pop()!=="("){return false;}break; 
13       case "}":
14         if(stack.pop()!=="{"){return false;} break;  
15       case "]":
16         if(stack.pop()!=="["){return false;}break; 
17       }
18     }
19   }
20   
21   if(stack.length==0){return true;}
22   else{return false;}
23 }

 

优秀答案:

1 function validBraces(braces){
2  while(/\(\)|\[\]|\{\}/g.test(braces)){braces = braces.replace(/\(\)|\[\]|\{\}/g,"")}
3  return !braces.length;
4 }
 1 function validBraces(braces){
 2   var matches = { '(':')', '{':'}', '[':']' };
 3   var stack = [];
 4   var currentChar;
 5 
 6   for (var i=0; i<braces.length; i++) {
 7     currentChar = braces[i];
 8 
 9     if (matches[currentChar]) { // opening braces
10       stack.push(currentChar);
11     } else { // closing braces
12       if (currentChar !== matches[stack.pop()]) {
13         return false;
14       }
15     }
16   }
17 
18   return stack.length === 0; // any unclosed braces left?
19 }

 

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

转载于:https://www.cnblogs.com/hiluna/p/8854187.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值