- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 56 lines of Java from the credited upstream file 591.java.
- The implementation visibly relies on work queue.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean isValid(String code) {3 if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>')4 return false;5 6 Deque<String> stack = new ArrayDeque<>();7 8 for (int i = 0; i < code.length(); ++i) {9 int closeIndex = 0;10 if (stack.isEmpty() && containsTag)11 return false;12 if (code.charAt(i) == '<') {13 14 if (!stack.isEmpty() && code.charAt(i + 1) == '!') {15 closeIndex = code.indexOf("]]>", i + 2);16 if (closeIndex < 0 || !isValidCdata(code.substring(i + 2, closeIndex)))17 return false;18 } else if (code.charAt(i + 1) == '/') { 19 closeIndex = code.indexOf('>', i + 2);20 if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 2, closeIndex), true))21 return false;22 } else { 23 closeIndex = code.indexOf('>', i + 1);24 if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 1, closeIndex), false))25 return false;26 }27 i = closeIndex;28 }29 }30 31 return stack.isEmpty() && containsTag;32 }33 34 private boolean containsTag = false;35 36 private boolean isValidCdata(final String s) {37 return s.indexOf("[CDATA[") == 0;38 }39 40 private boolean isValidTagName(Deque<String> stack, String tagName, boolean isEndTag) {41 if (tagName.isEmpty() || tagName.length() > 9)42 return false;43 44 for (final char c : tagName.toCharArray())45 if (!Character.isUpperCase(c))46 return false;47 48 if (isEndTag)49 return !stack.isEmpty() && stack.pop().equals(tagName);50 51 containsTag = true;52 stack.push(tagName);53 return true;54 }55}56