Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:

  1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
  2. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
  3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
  4. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
  5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
  6. < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).
  7. The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
  8. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.

Valid Code Examples:

Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
Output: True
Explanation:
The code is wrapped in a closed tag : <DIV> and </DIV>.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.
So TAG_CONTENT is valid, and then the code is valid. Thus return true. Input: "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
Output: True
Explanation:
We first separate the code into : start_tag|tag_content|end_tag.
start_tag -> "<DIV>"
end_tag -> "</DIV>"
tag_content could also be separated into : text1|cdata|text2.
text1 -> ">> ![cdata[]] "
cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"
text2 -> "]]>>]" The reason why start_tag is NOT "<DIV>>>" is because of the rule 6.
The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.

Invalid Code Examples:

Input: "<A>  <B> </A>   </B>"
Output: False
Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa. Input: "<DIV> div tag is not closed <DIV>"
Output: False Input: "<DIV> unmatched < </DIV>"
Output: False Input: "<DIV> closed tags with invalid tag name <b>123</b> </DIV>"
Output: False Input: "<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>"
Output: False Input: "<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>"
Output: False

Note:

  1. For simplicity, you could assume the input code (including the any characters mentioned above) only contain lettersdigits'<','>','/','!','[',']' and ' '.

Approach #1: Simulate. [Java]

class Solution {
public boolean isValid(String code) {
Stack<String> stack = new Stack<>();
int i, j;
for (i = 0; i < code.length(); ) {
if (i > 0 && stack.empty()) return false;
if (code.startsWith("<![CDATA[", i)) {
j = i + 9;
i = code.indexOf("]]>", j);
if (i < 0) return false;
i += 3;
} else if (code.startsWith("</", i)) {
j = i + 2;
i = code.indexOf(">", j);
if (i < 0 || i - j > 9 || i == j) return false;
for (int k = j; k < i; ++k)
if (!Character.isUpperCase(code.charAt(k))) return false;
String substr = code.substring(j, i++);
if (stack.empty() || !stack.pop().equals(substr)) return false;
} else if (code.startsWith("<", i)) {
j = i + 1;
i = code.indexOf(">", j);
if (i < 0 || i - j > 9 || i == j) return false;
for (int k = j; k < i; ++k)
if (!Character.isUpperCase(code.charAt(k))) return false;
String substr = code.substring(j, i++);
stack.push(substr);
} else {
i++;
}
}
return stack.empty();
}
}

  

Reference:

https://leetcode.com/problems/tag-validator/discuss/103368/Java-Solution%3A-Use-startsWith-and-indexOf

591. Tag Validator的更多相关文章

  1. [LeetCode] Tag Validator 标签验证器

    Given a string representing a code snippet, you need to implement a tag validator to parse the code ...

  2. [Swift]LeetCode591. 标签验证器 | Tag Validator

    Given a string representing a code snippet, you need to implement a tag validator to parse the code ...

  3. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  4. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  5. Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

    All LeetCode Questions List 题目汇总 Sorted by frequency of problems that appear in real interviews. Las ...

  6. leetcode 学习心得 (3)

    源代码地址:https://github.com/hopebo/hopelee 语言:C++ 517. Super Washing Machines You have n super washing ...

  7. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

  8. LeetCode All in One 题目讲解汇总(转...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通 ...

  9. [LeetCode] Add Bold Tag in String 字符串中增添加粗标签

    Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and ...

随机推荐

  1. ENVIRONMENT

    ENVIRONMENT Generalizations Congratulations! You learned to use the bash profile to configure the en ...

  2. ReactiveX 学习笔记(23)RxCpp

    RxCpp RxCpp 是 ReactiveX 的 C++ 语言实现. 下载 RxCpp $ git clone --recursive https://github.com/ReactiveX/Rx ...

  3. [Redis]Redis的五种数据类型与键值/服务器相关命令

    -------------------------------------------------------------------------------------- String(字符串):最 ...

  4. 37.Spring-事务控制.md

    目录 1.分类 2.Spring对jadc事务管理 2.1xml方式 2.1.1首先定义Dao对象和Server对象 2.1.2配置文件实现事务管理 2.2注解方式 2.2.1对象类 2.2.2配置文 ...

  5. Could not find a package configuration file provided by "Sophus",SophusConfig.cmake

    CMake Error at CMakeLists.txt:5 (find_package): By not providing "FindSophus.cmake" in CMA ...

  6. aptana怎么显示空格 tab和回车等

  7. EOS keosd

    [EOS keosd] The program keosd, located in the eos/build/programs/keosd folder within the EOSIO/eos r ...

  8. Anaconda3(python3.5.2)中安装opencv3

    1 安装Visual C++2015 redistributable 我是64位和32的都安装了,如果你电脑中已经安装了17的,就先卸载了,不然安装不上. 2 安装依赖包Numpy.Scipy Num ...

  9. Python设计模式 - 基础 - 封装 & 继承 & 多态

    面向对象的核心是对象,世间万物都可以看作对象,任何一个对象都可以通过一系列属性和行为来描述,可以包含任意数量和类型的数据或操作.类是用来描述具有相同属性和方法的所有对象的集合.类通常是抽象化的概念,而 ...

  10. MySQL 5.7.9版本sql_mode=only_full_group_by

    这会导致select中只能出现group by后面出现的表的字段. 其实如果使用其他表的字段,聚合函数对无法对应其他表的字段. 建议放在子查询里. 如果想打破这个规则,可以设置sql_mode变量,将 ...