题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
for(int i = 0;i<s.length();i++){
queue.add(s.charAt(i));
}
return solve(queue);
}
public int solve(LinkedList<Character> queue){
Stack<Integer> stack1 = new Stack<>();
char sign = '+';
int num = 0;
while(!queue.isEmpty()){
num = solve(queue);
num = num * 10 + ch-'0';
if(sign == '-'){
stack1.push(-num);
}else if(sign == '*'){
int num1 = stack1.pop();
stack1.push(num*num1);
}else if(sign == '+'){
stack1.push(num);
}
//更新符号,数字重置
sign = ch;
num = 0;
}
if(ch == ')'){
break;
}
while(!stack1.empty()){
ans += stack1.pop();
}
return ans;
}
}
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
// write code here
//将字符串放入队列中,可以解决递归返回下标不知道如何处理的问题
LinkedList<Character> queue = new LinkedList<>();for(int i = 0;i<s.length();i++){
queue.add(s.charAt(i));
}
return solve(queue);
}
public int solve(LinkedList<Character> queue){
Stack<Integer> stack1 = new Stack<>();
char sign = '+';
int num = 0;
while(!queue.isEmpty()){
char ch = queue.poll();
//遇见‘(’递归
if(ch == '('){num = solve(queue);
}
//计算数字
if(Character.isDigit(ch)){num = num * 10 + ch-'0';
}
//不是数字或者队列为空
if(!Character.isDigit(ch)||queue.size()==0){if(sign == '-'){
stack1.push(-num);
}else if(sign == '*'){
int num1 = stack1.pop();
stack1.push(num*num1);
}else if(sign == '+'){
stack1.push(num);
}
//更新符号,数字重置
sign = ch;
num = 0;
}
if(ch == ')'){
break;
}
}
//栈中的值求和返回
int ans = 0;while(!stack1.empty()){
ans += stack1.pop();
}
return ans;
}
}