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;
        }
    }
  • 相关阅读:
    hdu 4107 Gangster 线段树(成段更新)
    hdu 3037 Saving Beans (lucas定理)
    hdu 3944 DP? (Lucas 定理)
    hdu 5038 Grade 水
    ASP.NET Core 配置 MVC
    ASP.NET Core 静态文件
    ASP.NET Core 异常和错误处理
    ASP.NET Core 中间件
    ASP.NET Core 项目配置 ( Startup )
    ASP.NET Core 基本项目目录结构
  • 原文地址:https://www.cnblogs.com/haimishasha/p/11519417.html
Copyright © 2011-2022 走看看