一、问题
这里的四则运算字符串是指包含了+、-、*、/ 的的字符串,不包含括号,比如:"1+3-2*4/2"。如何用java解这种情景?
二、解法
我发现用递归方法代码是最简洁的,时间复杂度O(n),n为字符串长度。
下面是具体的解法:
public class Main{
public static void main(String[] args) {
String expression = "1+3-2*4/2";
System.out.println(calculate(expression));
}
private static boolean isNumber(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '.' && str.charAt(i) != ' ') {
return false;
}
}
return true;
}
private static double calculate(String str) {
if (str.isEmpty() || isNumber(str)) {
return str.isEmpty() ? 0 : Double.parseDouble(str);
}
if (str.contains("+")) {
int index = str.indexOf("+");
return calculate(str.substring(0, index)) + calculate(str.substring(index + 1));
}
if (str.contains("-")) {
int index = str.indexOf("-");
return calculate(str.substring(0, index)) - calculate(str.substring(index + 1));
}
if (str.contains("*")) {
int index = str.indexOf("*");
return calculate(str.substring(0, index)) * calculate(str.substring(index + 1));
}
if (str.contains("/")) {
int index = str.indexOf("/");
return calculate(str.substring(0, index)) / calculate(str.substring(index + 1));
}
return 0;
}
}
三、解释
递归方法就是不容易想,但是很简洁。+、- 计算是不分先后的,所以这两个判断顺序可以替换。同理 *、/ 也一样。但是+、- 必须在 *、/之前,这样才能让 *、/先进行计算。代码中第一个判断作用就是当没有运算符时,返回该数字。