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. ios unicode

    转义字符,反斜扛\ \u 后跟4位16进制数 \U 后跟8位16进制数

  2. 高性能迷你React框架anujs1.0.8发布

    本版本由于得到业务线同学的大力支持,掀出许多问题,因此改进地方良多,为anujs在完美替换React的道路上前进了不少.现在anujs经测试可以运行于IE7中.至少怎么做可以参看官网,https:// ...

  3. vue单页面处理SEO问题

    设置vue 单页面meta info信息 vue-meta-info,(https://github.com/muwoo/vue-meta-info)如果需要单页面SEO,可以和 prerender- ...

  4. 云笔记项目-AOP知识简单学习

    在云笔记项目的过程中,需要检查各个业务层的执行快慢,如登录.注册.展示笔记本列表,展示笔记列表等,如果在每个业务层方法里都写一段代码用来检查时间并打印,不仅仅显得代码重复,而且当项目很大的时候,将大大 ...

  5. Intellij IDEA中maven更新不下来pom中的jar包,reimport失效

    问题: Intellij IDEA中使用maven reimport包,一直失败 即使我将本地已存在的一个jar包目录删除了,pom文件那里也没飘红提示找不到  解决方法: maven设置中去掉离线下 ...

  6. 【Django】HTTP status code must be an integer.

    刚刚出现这个问题,还以为是表单提交或者什么网络错误 结果发现是自己的低级错误写了 HttpResponse(request,'sigin_result2.html',context)这个根本不能渲染模 ...

  7. C#删除文件夹以及删除文件

    public static void DelectDir(string srcPath) { try { DirectoryInfo dir = new DirectoryInfo(srcPath); ...

  8. Python开发——数据类型【字符串格式化】

    字符串格式化之——% # 字符串格式化 msg = 'I am %s , My hobby is %s'%('yuan','play') print(msg) # I am yuan , My hob ...

  9. Python开发——函数【作用域】

    变量的查找是由内向外的 # 全局变量 name = 'yuan' # 定义函数 def change1(): print(name) # yuan # 调用函数 change1() print(nam ...

  10. [TestNG] Eclipse/STS中两种安装TestNG的方法

    Two Ways To Install TestNG in Eclipse/STS Today I install the newest Sprint Tool Suite and want to i ...