`
zzq19860626
  • 浏览: 261091 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
博客专栏
B20df9e2-fb3d-3644-9f72-c1619842f682
设计模式学习笔记
浏览量:178009
87eaf24f-812a-3463-8e65-e3197d2ad8c2
java虚拟机
浏览量:26200
社区版块
存档分类
最新评论

判断表达式括号是否匹配java和js版本

阅读更多

 

 

本文转自:alaric's blog

 

昨天在群里有个同学问怎么校验括号是否匹配,
首先想到的是栈,遍历字符,如果遇到(,[,{就入栈,如果遇到),],}就弹出栈。很快代码如下实现了,这里要说的是java集合中有个栈这个数据结构,不需要自己再实现一个,所以比较快。代码如下:

package pipei;
import java.util.Stack;
/***
*
*【描述】:括号匹配
*【作者】:alaric
*【时间 】:Jun 4, 2012
*【文件】:pipeiMatching.java
*
*/
public class Matching {
public static boolean Match(String str){
char [] charArray = str.toCharArray();
Stack stack = new Stack();
for(char c: charArray){
if(c==’{‘||c==’['||c=='('){
stack.push(c);
}
if(c==')'||c==']‘||c==’}'){
Character cc= stack.pop();
switch(c){
case ‘)’: if(cc!=’(‘)return false;break;
case ‘]’: if(cc!=’[')return false;break;
case '}': if(cc!='{')return false;break;
}
}
}
return true;
}
/**
*【描述】:括号匹配测试
*【作者】:alaric
*【时间 】:Jun 4, 2012
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String string=”[[(()eeee)]]”;
if (Match(string)) {
System.out.println(“匹配”);
}else {
System.out.println(“不匹配”);
}
}
}
 

 

当我发出代码的时候,他说他要js写的,java看不懂,我崩溃,js实现个栈还是需要点时间的,于是拖到今天,终于有空实现下了,
代码如下:

<!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”).value
var 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 栈的实现,稍微有点麻烦,至少你要明白什么是栈这种数据结构,如果你了解了,这里这个代码不是很困难的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics