我正在尝试在java中编写一个方法来搜索我为特定字符导入的文本文件。该文件实际上是我设计并转换为.txt
文件的java程序。
当找到一个开口支架/支架时,我应该将它添加(推)到一个堆栈,然后当找到相应的关闭支架/支架时,我应该从堆栈中移除(弹出)它。
目的是查看我是否有正确数量的)
,}
,]
和>
与(
,{{ 1}},{
和[
。如果它们都匹配,则该方法应返回true,否则返回false。
任何人都知道我怎么写这个?
答案 0 :(得分:2)
这是用于平衡输入文本文件中括号的示例实现
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class BalanceBrackets {
private Stack<Character> symbolStack;
public void balance(String inputText) {
symbolStack = new Stack<Character>();
for (int index = 0; index < inputText.length(); index++) {
char currentSymbol = inputText.charAt(index);
switch (currentSymbol) {
case '(':
case '[':
case '{':
symbolStack.push(currentSymbol);
break;
case ')':
case ']':
case '}':
if (!symbolStack.isEmpty()) {
char symbolStackTop = symbolStack.pop();
if ((currentSymbol == '}' && symbolStackTop != '{')
|| (currentSymbol == ')' && symbolStackTop != '(')
|| (currentSymbol == ']' && symbolStackTop != '[')) {
System.out.println("Unmatched closing bracket while parsing " + currentSymbol + " at " + index+1);
return;
}
} else {
System.out.println("Extra closing bracket while parsing " + currentSymbol + " at character " + index+1);
return;
}
break;
default:
break;
}
}
if (!symbolStack.isEmpty())
System.out.println("Insufficient closing brackets after parsing the entire input text");
else
System.out.println("Brackets are balanced");
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("D://input.txt"));
String input = null;
StringBuilder sb = new StringBuilder();
while ((input = in.readLine()) != null) {
sb.append(input);
}
new BalanceBrackets().balance(sb.toString());
}
}