我想制作反向波兰表示法算法。我是通过使用Bauer和Samelson算法完成的,它运行成功,但它不适用于一元运算符(sin,cos,tan)。如何扩展此算法来处理它?</ p>
protected static Stack<String> convertToPolish(String in) {
Stack<String> inputString = new Stack<String>();
Stack<String> outputString = new Stack<String>();
Stack<String> store = new Stack<String>();
inputString.addAll(reverse(splitForExpressonsArray(in)));
while (!inputString.empty()) {
if (isNumber(inputString.peek()) {
outputString.push(inputString.pop());
} else if (isBinaryOperator(inputString.peek())) {
if (store.isEmpty()) {
store.push(inputString.pop());
} else if (getComparPriority(inputString.peek()) > getStorePriority(store.peek())) {
store.push(inputString.pop());
} else {
outputString.push(store.pop());
}
} else if (isBracket(inputString.peek())) {
if (inputString.peek().equals("(")) {
store.push(inputString.pop());
} else {
while (!store.peek().equals("(")) {
outputString.push(store.pop());
}
store.pop();
inputString.pop();
}
}
}
while (!store.isEmpty()) {
outputString.push(store.pop());
}
return outputString;
}
static Stack<String> splitForExpressonsArray(String input) {
Stack<String> result = new Stack<String>();
Matcher m = Pattern.compile("\\d+(?:\\.\\d+)?|[a-zA-Z]+|[^\\s\\w\\.]").matcher(in);
while (m.find()) {
result.add(m.group());
}
return result;
}
static int getComparPriority(String s) {
switch (s) {
case "(":
return 100;
case ")":
return 0;
case "+":
return 2;
case "-":
return 2;
case "*":
return 3;
case "/":
return 3;
default:
return 0;
}
}
static int getStorePriority(String s) {
switch (s) {
case "(":
return 0;
case "+":
return 2;
case "-":
return 2;
case "*":
return 3;
case "/":
return 3;
default:
return 0;
}
}
static boolean isBinaryOperator(String s) {
List<String> operators = Arrays.asList("+", "-", "*", "/");
return operators.contains(s);
}
static boolean isBracket(String s) {
List<String> brackets = Arrays.asList("(", ")");
return brackets.contains(s);
}
static boolean isUnarOperator(String s) {
List<String> operators = Arrays.asList("sin", "cos", "tan", "ctg");
return operators.contains(s);
}
static boolean isNumber(String peek) {
Pattern p = Pattern.compile("[0-9]*\\.?[0-9]");
Matcher m = p.matcher(peek);
return m.matches();
}
static Stack<String> reverse(Stack<String> split) {
Stack<String> result = new Stack<String>();
while (!split.isEmpty()) {
result.push(split.pop());
}
return result;
}