Search code examples
javadelimiter

How to determine if a text has balanced delimiters?


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;
        }
    }

Solution

  • 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();
      }
    
    }