问题描述:

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("()","")这种巧妙的方法确实没有想到。

最新文章

  1. jasmine test 页面测试工具
  2. TCP连接建立和终止小结
  3. 如何让vim编辑器永久显示行号
  4. Inside Flask - json 处理
  5. iOS开发-微博客户端-基本界面搭建(01)
  6. 转:Java NIO系列教程(九) Pipe
  7. /usr/include/gnu/stubs.h:7:27: error: gnu/stubs-32.h:No such file or directory的解决办法
  8. js与C#之间相互调用的一些方法
  9. java 读取文件到String(解决中文乱码)
  10. Cocos2dx开发(1)——Win8.1下 NDK r10 环境搭建
  11. redis使用Java学习
  12. Arch Linux 安装过程
  13. java运算符 与(&amp;)、非(~)、或(|)、异或(^)
  14. js面试题知识点全解(一变量类型和计算)
  15. windows环境Caffe安装配置步骤(无GPU)及mnist训练
  16. selenium 文件上传
  17. css设置垂直居中方式总结
  18. java.lang.LinkageError: JAXB 2.0 API is being loaded from the bootstrap classloader
  19. 创建一个Django项目的基本步骤
  20. Mac High Sierra 降级安装Mac Sierra

热门文章

  1. Flask登录认证
  2. ORM基础4 跨表查询+原子性操作
  3. [bzoj3527] [洛谷P3338] [Zjoi2014]力
  4. 插画版Kubernetes指南
  5. dotnet restore 初次运行 这个 指令 会安装 特别多的 4.0.0 或者 4.1 的 rc2-24027的 东东 这些东西。
  6. 个人第三次作业——结对编程 (姜玖林&amp;于丁)
  7. LeetCode-指针法
  8. Guava中强大的排序器Ordering使用
  9. Activity工作流框架入门(二)API使用DEMO
  10. vue的v-if和v-show的区别