/**
* 括号是否匹配 {} () []
*/
class IsMatch {
private char arr[];
private int maxSize;
private int top;
public IsMatch(int size){
maxSize = size;
arr = new char[maxSize];
top = -1;
}
//入栈
public void push(char value){
arr[++top] = value;
}
//出栈
public char pop(){
return arr[top--];
}
//判空
public boolean isEmpty(){
return top == -1;
}
}
class Match{
public static void check(String str){
int size = str.length();
IsMatch im = new IsMatch(size);
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
switch (ch){
case '{':
case '[':
case '(':
im.push(ch);
break;
case '}':
case ']':
case ')':
if(!im.isEmpty()){
char chx = im.pop();
if((ch == '}' && chx != '{') || (ch == ']' && chx != '[') || (ch == ')' && chx != '(') ){
System.out.println("括号不匹配:" + ch + "at:" + i);
}
}else {
System.out.println("括号不匹配:" + ch + "at:" + i);
}
break;
default:
break;
}
}
if(!im.isEmpty()){
System.out.println("Error:括号不匹配");
}
}
public static void main(String[] args){
String str1 = "{q[ss()]}";
String str2 = "s{[(fff]}";
// Match.check(str1);
Match.check(str2);
}
}
java版数据结构与算法—栈(判断括号是否匹配)
最新推荐文章于 2022-08-04 22:21:08 发布