美文网首页leetcode算法
591. 标签验证器 - 每日一题

591. 标签验证器 - 每日一题

作者: 刘翊扬 | 来源:发表于2022-05-02 23:42 被阅读0次

591. 标签验证器 - 力扣(LeetCode) (leetcode-cn.com)
给定一个表示代码片段的字符串,你需要实现一个验证器来解析这段代码,并返回它是否合法。合法的代码片段需要遵守以下的所有规则:

1. 代码必须被合法的闭合标签包围。否则,代码是无效的。
2. 闭合标签(不一定合法)要严格符合格式:<TAG_NAME>TAG_CONTENT</TAG_NAME>。其中,<TAG_NAME>是起始标签,</TAG_NAME>是结束标签。起始和结束标签中的 TAG_NAME 应当相同。当且仅当TAG_NAME 和 TAG_CONTENT 都是合法的,闭合标签才是合法的。
3. 合法的TAG_NAME仅含有大写字母,长度在范围 [1,9] 之间。否则,该TAG_NAME是不合法的。
4. 合法的TAG_CONTENT可以包含其他合法的闭合标签,cdata(请参考规则7)和任意字符(注意参考规则1)除了不匹配的<、不匹配的起始和结束标签、不匹配的或带有不合法 TAG_NAME 的闭合标签。否则,TAG_CONTENT是不合法的。
5. 一个起始标签,如果没有具有相同TAG_NAME 的结束标签与之匹配,是不合法的。反之亦然。不过,你也需要考虑标签嵌套的问题。
6. 一个<,如果你找不到一个后续的>与之匹配,是不合法的。并且当你找到一个<或</时,所有直到下一个>的前的字符,都应当被解析为TAG_NAME(不一定合法)。
7. cdata 有如下格式:<![CDATA[CDATA_CONTENT]]>。CDATA_CONTENT的范围被定义成<![CDATA[和后续的第一个]]>之间的字符。
8. CDATA_CONTENT可以包含任意字符。cdata 的功能是阻止验证器解析CDATA_CONTENT,所以即使其中有一些字符可以被解析为标签(无论合法还是不合法),也应该将它们视为常规字符。

合法代码的例子:

输入: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"

输出: True

解释: 

代码被包含在了闭合的标签内: <DIV> 和 </DIV> 。

TAG_NAME 是合法的,TAG_CONTENT 包含了一些字符和 cdata 。 

即使 CDATA_CONTENT 含有不匹配的起始标签和不合法的 TAG_NAME,它应该被视为普通的文本,而不是标签。

所以 TAG_CONTENT 是合法的,因此代码是合法的。最终返回True。


输入: "<DIV>>>  ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"

输出: True

解释:

我们首先将代码分割为: start_tag|tag_content|end_tag 。

start_tag -> "<DIV>"

end_tag -> "</DIV>"

tag_content 也可被分割为: text1|cdata|text2 。

text1 -> ">>  ![cdata[]] "

cdata -> "<![CDATA[<div>]>]]>" ,其中 CDATA_CONTENT 为 "<div>]>"

text2 -> "]]>>]"


start_tag 不是 "<DIV>>>" 的原因参照规则 6 。
cdata 不是 "<![CDATA[<div>]>]]>]]>" 的原因参照规则 7 。

不合法代码的例子:

输入: "<A>  <B> </A>   </B>"
输出: False
解释: 不合法。如果 "<A>" 是闭合的,那么 "<B>" 一定是不匹配的,反之亦然。

输入: "<DIV>  div tag is not closed  <DIV>"
输出: False

输入: "<DIV>  unmatched <  </DIV>"
输出: False

输入: "<DIV> closed tags with invalid tag name  <b>123</b> </DIV>"
输出: False

输入: "<DIV> unmatched tags with invalid tag name  </1234567890> and <CDATA[[]]>  </DIV>"
输出: False

输入: "<DIV>  unmatched start tag <B>  and unmatched end tag </C>  </DIV>"
输出: False

注意:

为简明起见,你可以假设输入的代码(包括提到的任意字符)只包含数字, 字母, '<','>','/','!','[',']'和' '。

栈 + 字符串遍历

class Solution {
    public boolean isValid(String code) {
        int n = code.length();
        Deque<String> tags = new ArrayDeque<String>();

        int i = 0;
        while (i < n) {
            if (code.charAt(i) == '<') {
                if (i == n - 1) {
                    return false;
                }
                if (code.charAt(i + 1) == '/') {
                    int j = code.indexOf('>', i);
                    if (j < 0) {
                        return false;
                    }
                    String tagname = code.substring(i + 2, j);
                    if (tags.isEmpty() || !tags.peek().equals(tagname)) {
                        return false;
                    }
                    tags.pop();
                    i = j + 1;
                    if (tags.isEmpty() && i != n) {
                        return false;
                    }
                } else if (code.charAt(i + 1) == '!') {
                    if (tags.isEmpty()) {
                        return false;
                    }
                    if (i + 9 > n) {
                        return false;
                    }
                    String cdata = code.substring(i + 2, i + 9);
                    if (!"[CDATA[".equals(cdata)) {
                        return false;
                    }
                    int j = code.indexOf("]]>", i);
                    if (j < 0) {
                        return false;
                    }
                    i = j + 1;
                } else {
                    int j = code.indexOf('>', i);
                    if (j < 0) {
                        return false;
                    }
                    String tagname = code.substring(i + 1, j);
                    if (tagname.length() < 1 || tagname.length() > 9) {
                        return false;
                    }
                    for (int k = 0; k < tagname.length(); ++k) {
                        if (!Character.isUpperCase(tagname.charAt(k))) {
                            return false;
                        }
                    }
                    tags.push(tagname);
                    i = j + 1;
                }
            } else {
                if (tags.isEmpty()) {
                    return false;
                }
                ++i;
            }
        }

        return tags.isEmpty();
    }
}

自己写的,效率比较低

public static boolean isValid(String code) {
        int preIndex = -1, endIndex = -1, len = code.length();
        for (int i = 0; i < code.length(); i++) {
            char ch = code.charAt(i);
            if (ch == '<') {
                if (i == 0) {
                    preIndex = i;
                } else {
                    return false;
                }
            }
            if (preIndex != -1 && ch == '>') {
                endIndex = i;
                break;
            }
        }
        if (len < 2 * (endIndex - preIndex + 1) - 1) {
            return false;
        }
        if (preIndex == -1 || endIndex == -1) {
            return false;
        }
        String preTag = code.substring(0, endIndex + 1);
        String endTag = code.substring(len - (endIndex - preIndex + 2), len);
        boolean tagValid = isValidTag(code.substring(0 + 1, endIndex));
        if (!tagValid || !compareTag(preTag, endTag)) {
            return false;
        }
        // 判断 cdata
        String cdata = code.substring(endIndex + 1, len - (endIndex - preIndex + 2));
        int cdataBeginIndex = cdata.indexOf("<![CDATA[");
        int cdataEndIndex = -1;
        if (cdataBeginIndex != -1) {
            cdataEndIndex = cdata.indexOf("]]>");
            if (cdataEndIndex == -1 || cdataEndIndex < cdataBeginIndex) {
                return false;
            }
        }
        // 注意:cdata里面的字符,不需要验证和考虑了
        int begin = -1, end = -1;
        Deque<String> stack = new ArrayDeque<>();
        StringBuilder tagStringBuilder = new StringBuilder();
        for (int i = 0; i < cdata.length(); i++) {
            char ch = cdata.charAt(i);
            if (cdataBeginIndex != -1 && cdataEndIndex != -1 && i >= cdataBeginIndex && i < cdataEndIndex + 3) {
                if (i == cdataEndIndex + 2) {
                    // 再找下一对
                    cdataBeginIndex = cdata.indexOf("<![CDATA[", i);
                    cdataEndIndex = cdata.indexOf("]]>", i);
                }
                // <A><B<![CDATA[asd]]>></B></A>
                if (begin == -1 && end == -1) {
                    continue;
                } else {
                    tagStringBuilder.append(ch);
                }
            }
            if (ch == '<') {
                begin = i;
            }
            if (begin != -1 && ch == '>') {
                end = i;
            }
            if (begin + 1 < len && begin != -1) {
                if (ch == '/' && begin + 1 == i) {
                    if (stack.isEmpty()) {
                        return false;
                    }
                } else if (ch != '<' && end == -1) {
                    tagStringBuilder.append(ch);
                }
            }
            if (end != -1) {
                String tag = tagStringBuilder.toString();
                // 判断tag内容是否符合全部大写,{1, 9}
                if (!isValidTag(tag)) {
                    return false;
                }
                // 如果tag 等于之前的tag,则直接pop出去
                if (!stack.isEmpty() && stack.peek().equals(tag)) {
                    stack.pop();
                } else {
                    stack.push(tag);
                }
                // 重置
                tagStringBuilder.setLength(0);
                begin = end = -1;
            }
        }
        return stack.isEmpty() && begin == -1 && end == -1;
    }


    static boolean isValidTag(String tag) {
        return Pattern.matches("[A-Z]{1,9}", tag);
    }

    static boolean compareTag(String beginTag, String endTag) {
        return beginTag.charAt(0) == '<' && endTag.charAt(0) == '<' && endTag.charAt(1) == '/' && beginTag.substring(1).equals(endTag.substring(2));
    }

相关文章

网友评论

    本文标题:591. 标签验证器 - 每日一题

    本文链接:https://www.haomeiwen.com/subject/pfcbyrtx.html