-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterviewQuestions.java
85 lines (73 loc) · 2.83 KB
/
InterviewQuestions.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package interviewquestions;
import java.util.Stack;
/**
*
* @author pandra3
* Peyton Andras
* LSU ID: 894914572
*
*/
public class InterviewQuestions {
public static void main(String[] args) {
System.out.println(IsBalancedExpression("{}"));
System.out.println(IsBalancedExpression("({({)})}"));
System.out.println(IsBalancedExpression("({})"));
System.out.println(EvaluateExpression("5 4 5 * + 5 /"));
System.out.println(EvaluateExpression("4 5 + 7 2 - *"));
}
public static boolean IsBalancedExpression(String input){
char[] chars = input.toCharArray();
Stack<Character> myStack = new Stack<>();
for(int i = 0; i < chars.length; i++){
if(chars[i] == '(' || chars[i] == '{')
myStack.push(chars[i]);
else if(chars[i] == ')' || chars[i] == '}'){
if(myStack.isEmpty())
return false;
char op = myStack.pop();
if (op == '(' && chars[i] != ')' || op == '{' && chars[i] != '}')
return false;
}
}
if(myStack.isEmpty())
return true;
return false;
}
public static double EvaluateExpression(String expression){
char[] chars = expression.toCharArray();
Stack<Integer> myStack = new Stack<>();
for(int i = 0; i < chars.length; i++){
if(Character.isDigit(chars[i]))
myStack.push(Character.getNumericValue(chars[i]));
else if(chars[i] == '+' || chars[i] == '-' || chars[i] == '/' || chars[i] == '*'){
if(myStack.size()<2){
System.out.print("Expression is invalid");
return 0;
}
int num1 = myStack.pop();
int num2 = myStack.pop();
if(chars[i]=='+')
myStack.push(num1 + num2);
else if (chars[i] == '-')
myStack.push(num2 - num1);
else if(chars[i] == '/')
myStack.push(num2 / num1);
else if (chars[i] == '*')
myStack.push(num1*num2);
else{
System.out.print("Expression is invalid");
break;
}
}
}
if(myStack.size()>1){
System.out.println("Expression is invalid");
return 0;
}
return myStack.pop();
}
}