问题
I have this question,
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.
I am coding in java by the way..
For each test line, output is "1" if it has balanced delimiters, "0" otherwise.
An example below,
4 --- 0
{123} --- 1
{qweqwe{sdad} --- 0
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.
Below is my code..
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;
}
}
回答1:
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();
}
}
回答2:
The general solution for this problem is to use a Stack. For each input string, starting with an empty stack:
- When an open bracket is encountered, push it into the stack.
- When a close bracket is encountered, pop from stack and compare with the close bracket to see whether they are a matching pair. If not, return
false. If yes, continue.
When you have finished going through the string, check whether the stack is empty. If yes, return true, else return false.
For the case of quotes ' and ", if you disallow a quote to be inside the same quote, and you don't consider escape syntax, then the solution should be the same.
来源:https://stackoverflow.com/questions/11610847/how-to-determine-if-a-text-has-balanced-delimiters