java版資料結構與演算法—棧(判斷括號是否匹配)
阿新 • • 發佈:2018-11-29
/**
* 括號是否匹配 {} () []
*/
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);
}
}