Skip to content

Instantly share code, notes, and snippets.

@ariG23498
Created July 9, 2019 12:41
Show Gist options
  • Save ariG23498/d5d007a9a4171d665a43fd3bb7cf6729 to your computer and use it in GitHub Desktop.
Save ariG23498/d5d007a9a4171d665a43fd3bb7cf6729 to your computer and use it in GitHub Desktop.
SPOJ
import java.io.*;
import java.util.*;
class ReversePolish {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
char[] arr = br.readLine().toCharArray();
Stack<Character> operator = new Stack<Character>();
StringBuilder sb = new StringBuilder();
char p0 = '^';
ArrayList<Character> p1 = new ArrayList<Character>();
p1.add('*');
p1.add('/');
ArrayList<Character> p2 = new ArrayList<Character>();
p1.add('+');
p1.add('-');
for (char a : arr) {
if (a >= 'a' && a <= 'z') {
sb = sb.append(a);
} else {
if (a == ')') {
while (!operator.isEmpty() && operator.peek() != '(') {
sb = sb.append(operator.pop());
}
operator.pop();
} else {
if (a == p0) {
operator.push(a);
} else if ((p1.contains(a) && p1.contains(operator.peek()))
|| (p1.contains(a) && p2.contains(operator.peek()))) {
while ((!operator.isEmpty() && operator.peek() != '(')
|| (!operator.isEmpty() && operator.peek() == p0)) {
sb = sb.append(operator.pop());
}
operator.push(a);
} else if (p2.contains(a) && p2.contains(operator.peek())) {
while ((!operator.isEmpty() && operator.peek() != '(')
|| (!operator.isEmpty() && operator.peek() == p0)
|| (!operator.isEmpty() && p1.contains(operator.peek()))) {
sb = sb.append(operator.pop());
}
operator.push(a);
}
else{
operator.push(a);
}
}
}
}
System.out.println(sb);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment