利用栈实现括号的匹配:
import java.util.Stack;
//假设字符串中仅有(){}[]这几种符号的搭配,实现括号的匹配算法。
//基本数据结构:栈,利用栈后进先出的特质
public class BracketMatch {
public static void main(String[] args)
{
String s="{}[(){}]";
System.out.print(Match(s));
}
static Boolean Match(String s)
{
char temp=0;
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++)
{
temp=s.charAt(i);
if(temp=='('||temp=='{'||temp=='[')
stack.push(s.charAt(i));
else
{
char top=stack.pop();
switch(temp)
{
case ')':
if(top=='(')
break;
else return false;
case ']':
if(top=='[')
break;
else return false;
case '}':
if (top=='{')
break;
else return false;
default:
break;
}
}
}
return true;
}
}