forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_591.java
62 lines (57 loc) · 2.11 KB
/
_591.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.fishercoder.solutions;
import java.util.ArrayDeque;
import java.util.Deque;
public class _591 {
public static class Solution1 {
/**
* Credit: https://discuss.leetcode.com/topic/91300/java-solution-use-startswith-and-indexof
*/
public boolean isValid(String code) {
Deque<String> stack = new ArrayDeque<>();
for (int i = 0; i < code.length(); ) {
if (i > 0 && stack.isEmpty()) {
return false;
}
if (code.startsWith("<![CDATA[", i)) {
int j = i + 9;//"<![CDATA[" length is 9
i = code.indexOf("]]>", j);
if (i < 0) {
return false;
}
i += 3;//"]]>" length is 3
} else if (code.startsWith("</", i)) {
int j = i + 2;
i = code.indexOf(">", j);
if (i < 0 || i == j || i - j > 9) {
return false;
}
for (int k = j; k < i; k++) {
if (!Character.isUpperCase(code.charAt(k))) {
return false;
}
}
String s = code.substring(j, i++);
if (stack.isEmpty() || !stack.pop().equals(s)) {
return false;
}
} else if (code.startsWith("<", i)) {
int j = i + 1;
i = code.indexOf(">", j);
if (i < 0 || i == j || i - j > 9) {
return false;
}
for (int k = j; k < i; k++) {
if (!Character.isUpperCase(code.charAt(k))) {
return false;
}
}
String s = code.substring(j, i++);
stack.push(s);
} else {
i++;
}
}
return stack.isEmpty();
}
}
}