题解 | #计算器(二)#

计算器(二)

http://www.nowcoder.com/practice/a9c170bfaf7349e3acb475d786ab1c7d

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int calculate (String s) {
        // write code here
        LinkedList<String> infix = new LinkedList<>();
        String[] strs = s.split("");
        for (String tmp : strs) {
            if ("+".equals(tmp) || "-".equals(tmp) || "*".equals(tmp) || "/".equals(tmp)) {
                infix.add(tmp);
            } else {
                if (!infix.isEmpty() && !("+".equals(infix.peekLast()) || "-".equals(infix.peekLast()) || "*".equals(infix.peekLast()) || "/".equals(infix.peekLast()))) {
                    String last = infix.peekLast();
                    infix.removeLast();
                    infix.add(last + tmp);
                } else {
                    infix.add(tmp);
                }
            }
        }
        LinkedList<String> suffix = new LinkedList<>();
        Stack<String> stack = new Stack<>();
        while (!infix.isEmpty()) {
            String tmp = infix.poll();
            if ("+".equals(tmp) || "-".equals(tmp) || "*".equals(tmp) || "/".equals(tmp)) {
                if ("+".equals(tmp) || "-".equals(tmp)) {
                    while (!stack.isEmpty()) {
                        suffix.add(stack.pop());
                    }
                    stack.push(tmp);
                } else {
                    while (!stack.isEmpty() && ("*".equals(stack.peek()) || "/".equals(stack.peek()))) {
                        suffix.add(stack.pop());
                    }
                    stack.push(tmp);
                }
            } else {
                suffix.add(tmp);
            }
        }
        while (!stack.isEmpty()) {
            suffix.add(stack.pop());
        }
        int ans = 0;
        while (!suffix.isEmpty()) {
            String tmp = suffix.poll();
            if ("+".equals(tmp) || "-".equals(tmp) || "*".equals(tmp) || "/".equals(tmp)) {
                int num1 = Integer.valueOf(stack.pop());
                int num2 = Integer.valueOf(stack.pop());
                if ("+".equals(tmp)) {
                    ans = num2 + num1;
                } else if ("-".equals(tmp)) {
                    ans = num2 - num1;
                } else if ("*".equals(tmp)) {
                    ans = num2 * num1;
                } else {
                    ans = num2 / num1;
                }
                stack.push(String.valueOf(ans));
            } else {
                stack.push(tmp);
            }
        }
        return Integer.valueOf(stack.pop());
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞
送花
回复
分享
发布于 2022-04-27 11:42

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务