mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
refactor: InfixToPostfix
(#5401)
This commit is contained in:
@ -1,19 +1,15 @@
|
||||
package com.thealgorithms.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class InfixToPostfix {
|
||||
private InfixToPostfix() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
assert "32+".equals(infix2PostFix("3+2"));
|
||||
assert "123++".equals(infix2PostFix("1+(2+3)"));
|
||||
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
|
||||
}
|
||||
|
||||
public static String infix2PostFix(String infixExpression) throws Exception {
|
||||
if (!BalancedBrackets.isBalanced(infixExpression)) {
|
||||
if (!BalancedBrackets.isBalanced(filterBrackets(infixExpression))) {
|
||||
throw new Exception("invalid expression");
|
||||
}
|
||||
StringBuilder output = new StringBuilder();
|
||||
@ -55,4 +51,10 @@ public final class InfixToPostfix {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static String filterBrackets(String input) {
|
||||
Pattern pattern = Pattern.compile("[^(){}\\[\\]<>]");
|
||||
Matcher matcher = pattern.matcher(input);
|
||||
return matcher.replaceAll("");
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user