您的位置:首页 > 其它

堆叠顺序 和 推断是否成对括号

2015-10-25 14:39 225 查看
public class SqStack {

public int[] data;
public int top;
public SqStack() {
data = new int[20];
top = -1;
}
public boolean empty() {
return top == -1;

}
public boolean push(int e) {
if(top == 19) {
return false;
}
top++;
data[top] = e;
return true;
}
public int[] pop() {
int[] arr = new int[2];
if(top == -1) {
arr[0] = 0;
return arr;
}
arr[0] = 1;
arr[1] = data[top--];
return arr;
}
public int[] top() {
int[] arr = new int[2];
if(top == -1) {
arr[0] = 0;
return arr;
}
arr[0] = 1;
arr[1] = data[top];
return arr;
}
public void display() {
for(int i=0; i<=top; i++) {
System.out.print(data[i]+ " ");
}
System.out.println();
}

public static void main(String[] args) {
SqStack ss = new SqStack();
System.out.println(ss.empty());
ss.push(2);
ss.push(3);
ss.display();
ss.pop();
ss.display();
ss.push(1);
ss.push(2);
ss.display();
ss.pop();
ss.push(4);
ss.display();
ss.top();
ss.display();

}

}


结果:

true
2 3
2
2 1 2
2 1 4
2 1 4


public class SqStack {

public int[] data;
public int top;
public SqStack() {
data = new int[20];
top = -1;
}
public boolean empty() {
return top == -1;

}
public boolean push(int e) {
if(top == 19) {
return false;
}
top++;
data[top] = e;
return true;
}
public int[] pop() {
int[] arr = new int[2];
if(top == -1) {
arr[0] = 0;
return arr;
}
arr[0] = 1;
arr[1] = data[top--];
return arr;
}
public int[] top() {
int[] arr = new int[2];
if(top == -1) {
arr[0] = 0;
return arr;
}
arr[0] = 1;
arr[1] = data[top];
return arr;
}
public void display() {
for(int i=0; i<=top; i++) {
System.out.print(data[i]+ " ");
}
System.out.println();
}

//检查括号是否配对
public boolean check(String s) {
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '(') {
push(1);
} else if(s.charAt(i) == ')') {
if(empty())
return false;
else
pop();
}
}
if(empty()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
SqStack ss = new SqStack();
String s = new String("(sd()f(() )d()j)");
System.out.println(ss.check(s));
s = new String("(sd()f(() ))d()j)");
System.out.println(ss.check(s));
s = new String("(sd()f((() )d()j)");
System.out.println(ss.check(s));

}

}


结果:

true
false
false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: