酷狗笔试题:补齐左括号(栈)

本文介绍了一种使用Java实现的表达式求值算法,通过两个栈分别存储左括号和右括号,以及操作数和运算符,来解析并重新构造带有括号的数学表达式,确保了表达式的正确计算顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述:

//输入1+2)*3-4)*5-6)))
//输出((1+2)*((3-4)*(5-6)))

代码:

import java.util.*;

public class G {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine().trim();
        String result = getfullstr(str);
        System.out.println(result);
    }

    public static String getfullstr(String str) {
        Stack<String> lefts = new Stack<>();
        Stack<String> rights = new Stack<>();
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '+' || c == '-' || c == '+' || c == '*' || c == '/') {
                rights.add(c + "");
            } else if (c == ')') {
                String lstr1 = lefts.pop();
                String lstr2 = lefts.pop();
                String rstr1 = rights.pop();
                lefts.add("(" + lstr2 + rstr1 + lstr1 + ")");
            } else if (Character.isDigit(chars[i])) {
                String num = c + "";
                while ((i + 1) < chars.length && Character.isDigit(chars[i + 1])) {
                    num += c;
                    i++;
                }
                lefts.add(num);
            }
        }
        while (rights.size() > 0) {
            String lstr1 = lefts.pop();
            String lstr2 = lefts.pop();
            String rstr1 = rights.pop();
            lefts.add("(" + lstr2 + rstr1 + lstr1 + ")");
        }
        String result = "";
        while (lefts.size() > 0) {
            result = lefts.pop() + result;
        }
        return result;
    }
}

 

转载于:https://www.cnblogs.com/haimishasha/p/11519417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值