1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public boolean isValid(String code) { int n = code.length(), i = 0; Deque<String> stack = new ArrayDeque<>(); 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 (stack.isEmpty() || !stack.peek().equals(tagName)) return false; stack.pop(); i = j + 1; if (stack.isEmpty() && i != n) return false; } else if (code.charAt(i + 1) == '!') { if (stack.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; } stack.push(tagName); i = j + 1; } } else { if (stack.isEmpty()) return false; ++i; } } return stack.isEmpty(); } }
|