判断表达式括号是否匹配java和js版本??本文转自:alarics blog?昨天在群里有个同学问怎么校验括号是否匹配
判断表达式括号是否匹配java和js版本
?
?
本文转自:alaric's blog
?
昨天在群里有个同学问怎么校验括号是否匹配,
首先想到的是栈,遍历字符,如果遇到(,[,{就入栈,如果遇到),],}就弹出栈。很快代码如下实现了,这里要说的是java集合中有个栈这个数据结构,不需要自己再实现一个,所以比较快。代码如下:
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”><html><head><meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″><title>Insert title here</title></head><body><script>function Stock(count){this.ptCount=-1;//指向最后一个数据的指针this.count=100;//容量this.myArray=new Array();if(count!=undefined){this.count=count;this.myArray=new Array(this.count);}else{this.count=0;}this.Info=function(mvalue)//进栈{if (this.ptCount == this.count){return false;}else{++this.ptCount;this.myArray[this.ptCount] = mvalue;return true;}return false;}this.Out=function()//出栈{if (this.ptCount == -1){return false;}else{var reObject;reObject = this.myArray[this.ptCount];this.ptCount–;return reObject;}}this.RLCount=function(){return this.ptCount + 1;}this.Clear=function(){this.ptCount=-1;}}function Match(str){var charArray =new Array();charArray= str.split(“”);var stack = new Stock(100);for(var i=0;i<charArray.length;i++){var c= charArray[i];if(c==’{‘||c==’['||c=='('){stack.Info(c);}if(c==')'||c==']‘||c==’}'){var cc= stack.Out();switch(c){case ‘)’: if(cc!=’(‘)return false;break;case ‘]’: if(cc!=’[‘)return false;break;case ‘}’: if(cc!=’{‘)return false;break;}}}if(stack.Out())return false;return true;}function test(){var str = document.getElementById(“strId”).valuevar b = Match(str);document.getElementById ( “outId” ).value=b;}</script><input type=”text” id=”strId” value=”"/><input type=”text” id=”outId” value=”"/><input type=”button” onclick=”test();” value=”submit” /></body></html>?js 栈的实现,稍微有点麻烦,至少你要明白什么是栈这种数据结构,如果你了解了,这里这个代码不是很困难的。
