如何确定文本是否具有平衡的定界符? [英] How to determine if a text has balanced delimiters?

查看:74
本文介绍了如何确定文本是否具有平衡的定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题

编写一个函数来确定文本是否具有平衡的定界符。有效的定界符对为(),[],{}和<>。它们可能是嵌套的。另外,确定文本定界符'和是否正确匹配。

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

}

这篇关于如何确定文本是否具有平衡的定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆