zoukankan      html  css  js  c++  java
  • 酷狗笔试题:补齐左括号(栈)

    描述:

    //输入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;
        }
    }
  • 相关阅读:
    线性筛2 筛约数个数
    背包板子
    线段树(指针板子)
    10.11 模拟赛(QBXT国庆Day3)
    10.6 体育成绩统计
    10.5 T3 DDP BZOJ 4712
    10.2模拟赛总结
    线性筛1
    CF165D Beard Graph
    2019 CSP-S第一轮(hsyz半日游)
  • 原文地址:https://www.cnblogs.com/haimishasha/p/11519417.html
Copyright © 2011-2022 走看看