Java-Part 0

Advanced Java and Cutting-edge Applications

Part 0: Course presentation

image-20240922221436556

Part 1

其实就是个括号匹配问题,Stack 经典问题,但是好久没用Java,有一点点生疏,感觉老师的版本要简洁的多

package tiei.ajp.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class CheckBalance {
    public String str;

    public CheckBalance() {
    }

    public CheckBalance(String string) {
        str = string;
    }

    public boolean balanced() {
        Stack<Character> stack = new Stack<>();
        char[] s = str.toCharArray();
        Map<Character, Integer> map = Map.of('(', 1, '[', 2, '{', 3, ')', 4, ']', 5, '}', 6);
        for (Character c : s) {
//            if ((c != '(') && (c != ')') && (c != '[') && (c != ']') && (c != '{') && (c != '}')) continue;
            if(!map.containsKey(c)) continue;
//            if (c == '(' || c == '{' || c == '[') {
            if (map.get(c) <= map.size() / 2) {
                stack.push(c);
            } else {
                if (stack.empty()) return false;
                char temp = stack.peek();
//                if ((temp == '(' && c == ')') || (temp == '[' && c == ']') || (temp == '{' && c == '}')) {
                if (map.get(c) - map.get(temp) == map.size() / 2) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.empty();
    }

    public int index() {
        Stack<Integer> stack = new Stack<>();
        char[] s = str.toCharArray();

        for (int i = 0; i < s.length; i++) {
            char c = s[i];
//            if (Character.isLetter(c) || c == ' ') continue;
            if ((c != '(') && (c != ')') && (c != '[') && (c != ']') && (c != '{') && (c != '}')) continue;

            if (c == '(' || c == '{' || c == '[') {
                stack.push(i);
            } else {

                if (stack.empty()) return i;

                char temp = s[stack.peek()];
                if ((temp == '(' && c == ')') || (temp == '[' && c == ']') || (temp == '{' && c == '}')) {
                    stack.pop();
                } else {
                    return i;
                }
            }
        }

        if (!stack.empty()) return stack.peek();

        return -1;
    }
}

老师版本:

package tiei.ajp.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class CheckBalance {
    private final String OPENINGS = "([{";
    private final String CLOSINGS = ")]}";

    private String s;
    private int index;
    private boolean balanced;

    public CheckBalance(String str) {
        this.s = str;
        balanced = balancedPrivate();
    }

    public boolean balanced(){
        return balanced;
    }

    private boolean balancedPrivate() {
        index = 0;
        Stack<Character> stack = new Stack<>();
        for (index = 0; index < s.length(); index++) {
            char c = s.charAt(index);
            if (isOpening(c)) {
                stack.push(c);
            } else if (isClosing(c)) {
                if (stack.empty() || dontMatch(stack.pop(), c)) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public int index() {
        return index;
    }

    private boolean isOpening(char c) {
        return OPENINGS.indexOf(c) > -1;
    }

    private boolean isClosing(char c) {
        return CLOSINGS.indexOf(c) > -1;
    }

    private boolean dontMatch(char o, char c) {
        return OPENINGS.indexOf(o) != CLOSINGS.indexOf(c);
    }
}
Part 2
package tiei.ajp.test;

public class ArrayStack {
    private static int MAX_SIZE = 100;
    private char[] stackArray;
    private int top;

    public ArrayStack(){
        stackArray = new char[MAX_SIZE];
        top = -1; 
    }
    public boolean isEmpty(){
        return top == -1;
    }
    public char peek(){
        if (isEmpty()) {
            return '\0';
        }
        return stackArray[top];
    }
    public void push(char c){
        if (top < MAX_SIZE - 1) {
            stackArray[++top] = c;
        }
    }
    public char pop(){
        if (isEmpty()) {
            return '\0';
        }
        return stackArray[top--];
    }
}
Part 3
package tiei.ajp.test;

public class ListStack {

    private class Node {
        char data;
        Node next;

        Node(char data) {
            this.data = data;
            this.next = null;
        }
    }

    private Node top;

    public ListStack() {
        top = null;
    }

    public boolean isEmpty() {
        return top == null;
    }


    public char peek() {
        if (isEmpty()) {
            return '\0';
        }
        return top.data;
    }


    public void push(char c) {
        Node newNode = new Node(c);
        newNode.next = top;
        top = newNode;
    }

    public char pop() {
        if (isEmpty()) {
            return '\0';
        }
        char popData = top.data;
        top = top.next;
        return popData;
    }
}

Test code
//
// Advanced Java Programming
// TIEI - Fall 2024
//
package tiei.ajp.test;

import java.util.*;
import tiei.ajp.test.CheckBalance;

/**
 * A TestCheckBalance class for the test
 * YOU MUST NOT CHANGE THIS CLASS!!!
 */
public class TestCheckBalance {
	
	// the expected answers from the user
	private static final String YES = "yes";
	private static final String NO  = "no";

	/**
	 * The main program
	 */
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Welcome to the Balance Checking Program");
		do {
			System.out.print("\nEnter the string you wish to check: ");
			String theString = input.nextLine();
			CheckBalance check = new CheckBalance(theString);
			if ( check.balanced() )
				System.out.println("The string is balanced!");
			else {
				System.out.println("The string is unbalanced:\n");
				System.out.println(theString);
				System.out.printf("%" + ( check.index() + 2 ) + "s", "^\n");
			}
			System.out.println();
		} while ( more(input) );
	}
	
	// Ask the user for more and return a boolean
	private static boolean more(Scanner input) {
		String answer = null;
		do {
			System.out.print("More ('" + YES + "' or '" + NO + "')? ");
			answer = input.nextLine().trim().toLowerCase();
		} while ( ! answer.equals(YES) && ! answer.equals(NO) );
		return answer.equals(YES);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值