活跃农民
- 积分
- 416
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-5-22
- 最后登录
- 1970-1-1
|
写了一下 假设没有负数的话 大概这样 请指点
- public static void main(String[] args) {
- System.out.println(Sexpression("(* (* 6(+ 5 8 6))(+ 9 ( * 2 2 )))"));
- //(* (* 6(+ 5 8 6))(+ 9 ( * 2 2 )))
- }
- public static int Sexpression(String s){
- Queue<Character> queue = new LinkedList<>();
- for(char c : s.toCharArray()){
- //if(c != ' '){
- queue.offer(c);
- //}
- }
- //queue.offer('+');
- return helper(queue);
- }
- public static int helper(Queue<Character> q){
- int res = 0;
- int num = 0;
- Stack<Integer> stack = new Stack<>();
- Stack<Character> sstack = new Stack<>();
- //sstack.push('+');
- while(!q.isEmpty()){
- char c = q.poll();
- if(Character.isDigit(c)){
- num = num * 10 + (c-'0');
- System.out.println(num);
- while(!q.isEmpty() && Character.isDigit(q.peek())){
- char tmp = q.poll();
- System.out.println(tmp);
- num = num * 10 + (tmp-'0');
- }
- stack.push(num);
- num = 0;
- }else if(c == '(') {
- stack.push(helper(q));
- }else if(c == ' '){
-
- continue;
- }else{
- if(c == '+' || c == '-' || c == '*' || c =='/'){
- //System.out.println(c);
- sstack.push(c);
- }
- num=0;
- if(c == ')'){
- break;
- }
- }
- }
- if(sstack.isEmpty())return res;
- char sign = sstack.pop();
- System.out.println(sign);
- if(stack.isEmpty())return res;
- if(sign == '*')res = 1;
- for(int s : stack){
- if(sign == '+'){
- res += s;
- }else if(sign == '-'){
- res -= s;
- }else if(sign == '*'){
- res *= s;
- }else if(sign == '/'){
- res /= s;
- }
- }
- System.out.println(res);
- return res;
- }
复制代码 |
|