-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomplierOutput.java
70 lines (59 loc) · 1.87 KB
/
complierOutput.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
63
64
65
66
67
68
69
70
/*
Code Compiler Output
You are developing a code compiler, and in that there must be a feature to check whether the parentheses in the code expression are balanced or not, i.e.
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
The following are some examples of code expressions with balanced parentheses:
"if(arr(4) > 9) { foo(arr[2]); }"
"for(i=0; i<a[0]; i++) { a[i]++; }"
In the following examples, parentheses are not balanced:
"while(true) ) { foo( }; )"
"if(x) {"
Given a code expression, check whether it is containing balanced parentheses or not, and accordingly print the compiler output as "Success" or "Error".
*/
class Result {
static boolean compilerOutput(String code) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i<code.length(); i++){
if(code.charAt(i) == '('){
stack.push('(');
continue;
}
if(code.charAt(i) == '['){
stack.push('[');
continue;
}
if(code.charAt(i) == '{'){
stack.push('{');
continue;
}
if(code.charAt(i) == ')'){
if(stack.empty() == true || stack.peek() != '(')
return false;
else{
stack.pop();
}
continue;
}
if(code.charAt(i) == ']'){
if(stack.empty() == true || stack.peek() != '[')
return false;
else{
stack.pop();
}
continue;
}
if(code.charAt(i) == '}'){
if(stack.empty() == true || stack.peek() != '{')
return false;
else{
stack.pop();
}
continue;
}
}
if(stack.empty() == false)
return false;
return true;
}
}