-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
74 lines (70 loc) · 2.19 KB
/
Copy pathSolution.java
File metadata and controls
74 lines (70 loc) · 2.19 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Stack;
public class Solution
{
private static final String CDATA_START = "<![CDATA[";
private static final String CDATA_END = "]]>";
private static final String OPEN_TAG = "<";
private static final String CLOSE_TAG = "</";
private static final String END_TAG = ">";
public boolean isValid(String code)
{
Stack<String> stack = new Stack<String>();
for (int i = 0; i < code.length(); )
{
if (i > 0 && stack.isEmpty())
{
return false;
}
if (code.startsWith(CDATA_START, i))
{
int idx = code.indexOf(CDATA_END, i + CDATA_START.length() - 1);
if (idx == -1)
{
return false;
}
i = idx + CDATA_END.length();
}
else if (code.startsWith(CLOSE_TAG, i))
{
int idx = code.indexOf(END_TAG, i + CLOSE_TAG.length() - 1);
if (idx == -1)
{
return false;
}
String s = code.substring(i + CLOSE_TAG.length(), idx);
if (stack.isEmpty() || !stack.pop().equals(s))
{
return false;
}
i = idx + END_TAG.length();
}
else if (code.startsWith(OPEN_TAG, i))
{
int idx = code.indexOf(END_TAG, i + OPEN_TAG.length() - 1);
if (idx == -1)
{
return false;
}
String s = code.substring(i + OPEN_TAG.length(), idx);
if (s.isEmpty() || s.length() < 1 || s.length() > 9)
{
return false;
}
for (char c : s.toCharArray())
{
if (!Character.isUpperCase(c))
{
return false;
}
}
stack.add(s);
i = idx + END_TAG.length();
}
else
{
i++;
}
}
return stack.isEmpty();
}
}