题目:
给出如下串:sum(sum(sum(1,2),avg(3,5)),avg(avg(6,8),7)), 计算结果(保证输入任意上述接口均能输出正确结果)
思路:
![](https://i-blog.csdnimg.cn/blog_migrate/1fe1d296c74012215a0ee07e8221d798.jpeg)
编辑
代码:
import java.util.Stack;
public class Test {
public static String sum = "sum";
public static String avg = "avg";
public static String s1 = "sum(sum(sum(1,2),avg(3,5)),avg(avg(6,8),7))";
public static void main(String[] args) {
System.out.println(parseByStack(s1));;
}
/**
*
* @param s
* @return
*/
public static float parseByStack(CharSequence s) {
Stack<String> operators = new Stack<>();
Stack<Float> numbers = new Stack<>();
int index = 0;
while (index < s.length()) {
if (s.charAt(index) == 's' && s.charAt(index + 1) == 'u' && s.charAt(index + 2) == 'm') {
operators.push(sum);
index += 3;
} else if (s.charAt(index) == 'a' && s.charAt(index + 1) == 'v' && s.charAt(index + 2) == 'g') {
operators.push(avg);
index += 3;
} else if (Character.isDigit(s.charAt(index))) {
StringBuilder sb = new StringBuilder();
while (Character.isDigit(s.charAt(index))) {
sb.append(s.charAt(index));
index++;
}
numbers.push(Float.parseFloat(sb.toString()));
} else if (s.charAt(index) == ')') {
// 遇见左括号时,需要处理数据
var operator = operators.pop();
if (operator.equals(sum)) {
numbers.push(numbers.pop() + numbers.pop());
} else if (operator.equals(avg)) {
numbers.push((numbers.pop() + numbers.pop()) / 2);
}
index++;
} else {
// s.charAt(index) == '(' || s.charAt(index) == ','
index++;
}
}
return numbers.pop();
}
}