题目
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:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
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.
A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
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.
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.
A < 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).
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 ]]>.
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.
答案
class Solution {
public boolean isValid(String code) {
// Store current tag's name
Stack<String> stk = new Stack<>();
String tag_name = "";
for(int i = 0; i < code.length(); i++) {
if(i > 0 && stk.isEmpty()) return false;
if(code.substring(i, Math.min(i + 9, code.length())).equals("<![CDATA[")) {
// Look for end of CDATA
int t = i + 9;
i = code.indexOf("]]>", t);
if(i < 0) return false;
i = i + 2;
}
else if(code.substring(i, Math.min(i + 2, code.length())).equals("</")) {
// Look for '>'
int t = i + 2;
i = code.indexOf(">", t);
if(i < 0) return false;
tag_name = code.substring(t, i);
if(stk.isEmpty() || !tag_name.equals(stk.peek())) return false;
stk.pop();
}
else if(code.substring(i, Math.min(i + 1, code.length())).equals("<")) {
// Look for '>'
int t = i + 1;
i = code.indexOf(">", t);
if(i < 0) return false;
tag_name = code.substring(t, i);
if(tag_name.length() < 1 || tag_name.length() > 9) return false;
for(int j = 0; j < tag_name.length(); j++) {
if(!Character.isUpperCase(tag_name.charAt(j))) return false;
}
stk.push(tag_name);
}
}
return stk.isEmpty();
}
}
网友评论