算法场景:
如果我们笔试面试遇到四则运算算法题,需要使用字符串,栈等相关数据结构解决,如果你一时间逻辑混乱了,一直写不出来怎么办啊?不慌,今天我来教你一招。
算法原题:
常规解法:
牛客网四则运算:
常规解法代码:
import java.io.*;
import java.util.Stack;
public class Main{
static int pos;
public static int compute(String s){
char ops = '+';
int num = 0;
Stack<Integer> val = new Stack<>();
int temp;
while(pos < s.length()){
if(s.charAt(pos) == '{' || s.charAt(pos) == '[' || s.charAt(pos) == '('){
pos++;
num = compute(s);
}
while(pos < s.length() && Character.isDigit(s.charAt(pos))){
num = num * 10 + s.charAt(pos) - '0';
pos++;
}
switch (ops){
case '+':
val.push(num);
break;
case '-':
val.push(-num);
break;
case '*':
temp = val.pop();
temp = temp * num;
val.push(temp);
break;
case '/':
temp = val.pop();
temp = temp / num;
val.push(temp);
break;
}
num = 0;
if(pos < s.length()) {
ops = s.charAt(pos);
if(s.charAt(pos) == '}' || s.charAt(pos) == ']' || s.charAt(pos) == ')'){
pos++;
break;
}
}
pos++;
}
int sum = 0;
while(!val.isEmpty()){
sum += val.pop();
}
return sum;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
pos = 0;
System.out.println(compute(str));
}
}
就想问你,你面试笔试可以解决吗?如果你是大神,就当我没有说。。。。(小声BB);
救命方法:
1.我们可以利用js引擎来帮我们解决;
解法一:
import javax.script.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws ScriptException{
Scanner scan = new Scanner(System.in);
ScriptEngineManager res = new ScriptEngineManager();
ScriptEngine se = res.getEngineByName("js");
while(scan.hasNextLine()){
String s = scan.nextLine();
//替换括号
s = s.replace("[","(");
s = s.replace("]",")");
s = s.replace("{","(");
s = s.replace("}",")");
//执行js代码,并打印返回值
System.out.println(se.eval(s));
}
}
}
运行成功截图:
解法二:
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main{
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(input);
System.out.println(result.toString());
}
scanner.close();
}
}
运行成功截图:
结论:
如果遇到笔试,直接上代码,如果遇到面试,如果面试官没有说,那还等什么,就是时间空间不是很理想;
使用方法:我们需要将要计算的序列处理成类似于这种1+2*{1+2*[-4/(8-6)+7]};然后将该序列作为参数传递给上述代码块中即可;