如何确定文本是否具有平衡的定界符?
我有这个问题
编写一个函数来确定文本是否具有平衡的定界符。有效的定界符对为(),[],{}和<>。它们可能是嵌套的。另外,确定文本定界符'和是否正确匹配。
Write a function to determine if a text has balanced delimiters. The pairs of valid delimiters are (), [], {}, and <>. They may be nested. In addition, determine that text delimiters ' and " are properly matched.
我正在用Java进行编码。
I am coding in java by the way..
对于每条测试线,如果它具有平衡的定界符,则输出为 1,否则为 0。
For each test line, output is "1" if it has balanced delimiters, "0" otherwise.
下面的示例,
4 --- 0
{123} --- 1
{qweqwe{sdad} --- 0
问题是,如何用Java代码编写,以检查是否抱歉,我对分隔符知之甚少。
The problem, is, how can I write in java code, to check whether the pair of valid delimiters are matched? Sorry, I have very little knowledge of delimiters.
下面是我的代码。
public static void main(String args[]) {
String a1 = "";
try {
Scanner readFile = new Scanner(new File("2.in.txt"));
while (readFile.hasNextLine()) {
a1 = readFile.nextLine();
System.out.println(a1);
if (a1.equals("18")) {
System.out.println("0");
} else {
System.out.println("1");
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return;
}
}
有看看此代码,它可以解决类似的任务。
Have a look at this code, it solves a similar task.
import java.util.Stack;
class BracketChecker {
private String input;
public BracketChecker(String in) {
input = in;
}
public void check() {
Stack<Character> theStack = new Stack<Character>();
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("Error: missing right delimiter");
}
}
}
public class MainClass {
public static void main(String[] args) {
String input;
input = "[]]()()";
BracketChecker theChecker = new BracketChecker(input);
theChecker.check();
}
}