java通过堆栈实现字符串匹配

时间:2022-05-06
本文章向大家介绍java通过堆栈实现字符串匹配,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package stack;

public class StackZiFuPiPei {
	public int maxSize;
	public char[] array;
	public int top;

	public StackZiFuPiPei(int maxSize) {
		this.maxSize = maxSize;
		array = new char[maxSize];
		this.top = -1;
	}

	public void push(char c) {
		array[++top] = c;
	}

	public char pop() {
		return (array[top--]);
	}

	public char peak() {
		return (array[top]);
	}

	public boolean isEmpty() {
		return (top == -1);
	}

	public boolean isFull() {
		return (top == maxSize - 1);
	}
}

package stack;

import java.util.Scanner;

public class ZiFuPiPei {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Input a string:");
		String s = scanner.next();
		char[] c = s.toCharArray();
		StackZiFuPiPei stack = new StackZiFuPiPei(s.length());
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '(' || c[i] == '[' || c[i] == '{') {
				stack.push(c[i]);
			}
		}
		boolean b = true;
		for (int i = 0; i < c.length; i++) {
			if ((c[i] == ']' && stack.pop() != '[')
					|| (c[i] == ')' && stack.pop() != '(')
					|| (c[i] == '}' && stack.pop() != '{'))
				b = false;
		}
		if (b)
			System.out.println("字符匹配!");
		else
			System.out.println("字符不匹配!");
	}
}