这篇文章主要介绍“通过栈校验分隔符匹配的方法”,在日常操作中,相信很多人在通过栈校验分隔符匹配的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”通过栈校验分隔符匹配的方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
package helloclean;
public class StackX {
private int maxSize;
private char[] stackArray;
private int top;
public StackX(int max){
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
package helloclean;
public class BracketChecker {
private String input;
public BracketChecker(String in) {
this.input = in;
}
public void check() {
int stackSize = input.length();
StackX theStack = new StackX(stackSize);
for(int j = 0; j < input.length(); j ++) {
char ch = input.charAt(j);
switch (ch) {
case '{':
case '[':
case '(':
theStack.push(ch);
break;
case '}':
case ']':
case ')':
if(!theStack.isEmpty()) {
char chx = theStack.pop();
if((ch == '}' && chx != '{') || (ch == ')' && chx != '(') ||
ch == ']' && chx != '[') {
System.out.println("Error : " + ch + " at : " + j);
}
} else {
System.out.println("Error : " + ch + " at : " + j);
}
break;
default:
break;
}
}
if(!theStack.isEmpty()) {
System.out.println("missing right delimiter!");
}
}
}
package helloclean;
import java.util.Scanner;
public class BracketApp {
public static void main(String[] args) {
String input;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("input : eg: (ab[cd]e{fg})");
input = scanner.nextLine();
if(input.equals("q")) {
System.out.println("退出!");
break;
}
BracketChecker bracketChecker = new BracketChecker(input);
bracketChecker.check();
}
}
}
input : eg: (ab[cd]e{fg})
abc(de)[fg]{xxxxx
missing right delimiter!
input : eg: (ab[cd]e{fg})
abc[ef]ggg)dd
Error : ) at : 10
input : eg: (ab[cd]e{fg})
abc(x)d
input : eg: (ab[cd]e{fg})
到此,关于“通过栈校验分隔符匹配的方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4118445/blog/3106750