当前位置: 代码迷 >> 综合 >> HTML标签匹配,要点:Stack,StringTokenizer
  详细解决方案

HTML标签匹配,要点:Stack,StringTokenizer

热度:93   发布时间:2023-12-18 18:49:52.0
package dsa;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;/** 判断HTML文件中的标签匹配,使用栈,在终端中输入文件内容,按ctrl+z结束*/
public class Html {public static class Tag {String name;boolean opening;public Tag() {name = "";opening = false;}public Tag(String n, boolean type) {name = n;opening = type;}public boolean isOpening() {return opening;}public String getName() {return name;}}public void indent(int level) {// 匹配标记的层次,可能是多层嵌套for (int k = 0; k < level; k++)System.out.println("\t|");}public boolean isHtmlMatched(Tag[] tag) {// 检查每个起始标签是否对应一个结束标记int level = 0;Stack<String> s = new Stack<String>();for (int i = 0; (i < tag.length) && (tag[i] != null); i++) {if (tag[i].isOpening()) {s.push(tag[i].getName());indent(level++);System.out.println("\t" + tag[i].getName());} else {if (s.empty()) {return false;}if (!((String) s.pop()).equals(tag[i].getName()))return false;indent(--level);System.out.println("\t" + tag[i].getName());}}if (s.empty())return true;elsereturn false;}public final static int CAPACITY = 1000;// 从HTML文档中提取出标记,依次存入数组中public Tag[] parseHtml(BufferedReader r) throws IOException {String line;boolean inTag = false;// 是否扫描到标记Tag[] tag = new Tag[CAPACITY];int count = 0;while ((line = r.readLine()) != null) {StringTokenizer st = new StringTokenizer(line, "<> \t", true);while (st.hasMoreElements()) {String token = (String) st.nextToken();if (token.equals("<"))inTag = true;else if (token.equals(">"))inTag = false;else if (inTag) {if ((token.length() == 0) || (token.charAt(0) != '/'))tag[count++] = new Tag(token, true);elsetag[count++] = new Tag(token.substring(1), false);}}}return tag;}public static void main(String[] args) throws IOException {BufferedReader stdr = new BufferedReader(new InputStreamReader(System.in));// 标准输入Html tagChecker = new Html();if (tagChecker.isHtmlMatched(tagChecker.parseHtml(stdr)))System.out.println("该文件符合HTML标记匹配。");elseSystem.out.println("该文件不符合HTML标记匹配。");}
}

  相关解决方案