Expresión de cálculo [algoritmo de aprendizaje]
Prefacio
2023-9-24 23:02:07
El siguiente contenido es de "[Algoritmo de aprendizaje]"
y está destinado únicamente a fines de aprendizaje y comunicación.
derechos de autor
Elimine las siguientes palabras cuando publique en otras plataformas.
Este artículo se publicó por primera vez en la plataforma CSDN.
El autor es CSDN@日星月云.
La página de inicio del blog es https://blog.csdn.net/qq_51625007
. Elimine las siguientes palabras palabras anteriores al publicar en otras plataformas.
recomendar
ninguno
Expresión de cálculo
Evaluación de expresión polaca inversa
150. Evaluación de expresiones polacas inversas
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack();
for(String s:tokens){
if(s.equals("+")){
int b=Integer.parseInt(stack.pop());
int a=Integer.parseInt(stack.pop());
int c=a+b;
stack.push(Integer.toString(c));
}else if(s.equals("-")){
int b=Integer.parseInt(stack.pop());
int a=Integer.parseInt(stack.pop());
int c=a-b;
stack.push(Integer.toString(c));
}else if(s.equals("*")){
int b=Integer.parseInt(stack.pop());
int a=Integer.parseInt(stack.pop());
int c=a*b;
stack.push(Integer.toString(c));
}else if(s.equals("/")){
int b=Integer.parseInt(stack.pop());
int a=Integer.parseInt(stack.pop());
int c=a/b;
stack.push(Integer.toString(c));
}else{
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}
Evaluación de expresiones infijas
Pregunta de la entrevista 16.26 Calculadora
Código Leet
class Solution {
public int calculate(String s) {
Deque<Integer> stack = new ArrayDeque<Integer>();
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
if (Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
}
if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == n - 1) {
switch (preSign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
default:
stack.push(stack.pop() / num);
}
preSign = s.charAt(i);
num = 0;
}
}
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
}
análisis de prioridad del algoritmo
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
public class Solution {
public static void main(String[] args) {
String token="3/2";
int res=calculate(token);
System.out.println(res);
}
static HashSet<Character> opSet =new HashSet<>();
static {
opSet.add('#');
opSet.add('+');
opSet.add('-');
opSet.add('*');
opSet.add('/');
opSet.add('(');
opSet.add(')');
}
static HashMap<Character,HashMap<Character,Character>> relation=new HashMap<>();
static {
HashMap<Character,Character> map=new HashMap<>();
map.put('+','>');
map.put('-','>');
map.put('*','<');
map.put('/','<');
map.put('(','<');
map.put(')','>');
map.put('#','>');
relation.put('+',map);
relation.put('-',map);
map=new HashMap<>();
map.put('+','>');
map.put('-','>');
map.put('*','>');
map.put('/','>');
map.put('(','<');
map.put(')','>');
map.put('#','>');
relation.put('*',map);
relation.put('/',map);
map=new HashMap<>();
map.put('+','<');
map.put('-','<');
map.put('*','<');
map.put('/','<');
map.put('(','<');
map.put(')','=');
relation.put('(',map);
map=new HashMap<>();
map.put('+','>');
map.put('-','>');
map.put('*','>');
map.put('/','>');
map.put(')','>');
map.put('#','>');
relation.put(')',map);
map=new HashMap<>();
map.put('+','<');
map.put('-','<');
map.put('*','<');
map.put('/','<');
map.put('(','<');
map.put('#','=');
relation.put('#',map);
}
public static int calculate(String s) {
s = s.replaceAll("\\s+","");
s += '#';
Deque<Integer> numStack = new ArrayDeque<>();
Deque<Character> opStack = new ArrayDeque<>();
opStack.push('#');
int i = 0;
char ch = s.charAt(i);
while (ch != '#' || opStack.peek() != '#') {
if (!opSet.contains(ch)) {
while (ch == ' ') {
ch = s.charAt(++i);
}
int data = 0;
data = ch - '0';
ch = s.charAt(++i);
while (!opSet.contains(ch)) {
data = data * 10 + ch - '0';
ch = s.charAt(++i);
}
numStack.push(data);
} else {
switch (compare(opStack.peek(), ch)) {
case '<':
opStack.push(ch);
ch = s.charAt(++i);
break;
case '=':
char x = opStack.pop();
ch = s.charAt(++i);
break;
case '>':
char op = opStack.pop();
Integer data2 = numStack.pop();
Integer data1 = numStack.pop();
int val = cal(data1, op, data2);
numStack.push(val);
break;
}
}
}
int val = numStack.pop();
return val;
}
private static int cal(Integer data1, char op, Integer data2) {
switch (op){
case '+': return data1+data2;
case '-': return data1-data2;
case '*': return data1*data2;
case '/': return data1/data2;
default: return 0;
}
}
private static char compare(char op1, char op2) {
return relation.get(op1).get(op2);
}
}
por fin
Todos tenemos un futuro brillante
Les deseo todo lo mejor en sus exámenes de ingreso a posgrado, les deseo todo el éxito
en su trabajo, les deseo a todos lo que desean, me gusta, recopila y sigue.