Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class MyStack {
- public static void main(String[] args) {
- test(")", false);
- test("(", false);
- test("()", true);
- test("(()", false);
- test("(())", true);
- test("((())", false);
- test("(()()(()(()())()))", true);
- test("(()()(()(()())())))", false);
- }
- private static void test(String str, boolean expected) {
- if(expected == isParenthesisMatch(str)) {
- System.out.println(String.format(
- "OK:\t'%s'", str
- ));
- } else {
- System.err.println(String.format(
- "FAIL:\t'%s'", str
- ));
- }
- }
- private int maxSize;
- private List<String> container;
- public MyStack(int maxSize) {
- this.maxSize = maxSize;
- container = new ArrayList<>();
- }
- public MyStack() {
- this(10);
- }
- public void push(String n) {
- if (isFull()) {
- System.err.println("stack is full " + n);
- } else {
- container.add(n);
- }
- }
- public String pop() {
- if (container.isEmpty()) {
- System.err.println("stack is empty");
- return null;
- } else {
- int index = container.size() - 1;
- String result = container.remove(index);
- return result;
- }
- }
- public String peek() {
- if (container.isEmpty()) {
- System.err.println("stack is empty");
- return null;
- } else {
- int index = container.size() - 1;
- return container.get(index);
- }
- }
- public boolean isFull() {
- return container.size() == maxSize;
- }
- public boolean isEmpty() {
- return container.isEmpty();
- }
- public void empty() {
- container.clear();
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder(maxSize);
- sb.append("[ ");
- for (int i = 0; i < container.size(); i++) {
- sb.append(container.get(i)).append(" ");
- }
- sb.append("]");
- return sb.toString();
- }
- public boolean isParenthesisMatch(String str) {
- if ("(".equals(str)) {
- this.push(str);
- }
- if (this.isEmpty()) {
- return false;
- }
- if ("(".equals(this.peek())) {
- this.pop();
- }
- return this.isEmpty();;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement