Repository navigation
Expand file tree
/
Copy pathONP.java
More file actions
72 lines (60 loc) · 1.64 KB
/
Copy pathONP.java
File metadata and controls
72 lines (60 loc) · 1.64 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
package com.algo.problems;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
/**
* Generates Reverse Polish Notation(RPN) from an algebraic expression
* @author NM
*
*/
public class ONP {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int lines = in.nextInt();
//String onpString = "(a+(c/d))";
//String onpString = "((a+b)*(c/d))";
//String onpString = "((((a+c)+b)^(c+d))*(a+t))";
//String onpString = "((a+t)*((b+(a+c))^(c+d)))";
String onpString = "(((b+(a+c))^(c+d))*(a+t))";
//String onpString = "(((a+c)^(b+(c+d)))*(a+t))";
System.out.println(outputRPN(expression));
}
/**
* Generates RPN of algebraic expression.
*
*/
private static String outputRPN(String onpString) {
StringBuffer output = new StringBuffer();
if(onpString != null && !onpString.trim().isEmpty()) {
Stack<Character> operatorStack = new Stack<Character>();
for(int index=0; index < onpString.length(); index++) {
switch (onpString.charAt(index)) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '(':
operatorStack.add(onpString.charAt(index));
break;
case ')':
// Pop all elements from stack till first '('
// and add to output except ')' and '('
char pop = operatorStack.pop();
while(pop != '(') {
output.append(pop);
pop = operatorStack.pop();
}
break;
default:
output.append(onpString.charAt(index));
break;
}
}
while (!operatorStack.isEmpty()) {
output.append(operatorStack.pop());
}
}
return output.toString();
}
}