您的位置:首页 > 编程语言 > Java开发

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

2012-10-04 00:00 483 查看
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("字符不匹配!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息