「携程9.9Java后端笔试」模拟Linux命令行

cd a
cd ..
pwd
大致这三个切换问题的实现,和大家分享
使用stack栈实现,
cd x 就入栈,cd .. 就出栈,栈为空时就打印 /
注意pwd需要在前面补上 / 

package com.nowcoder.seckill.sort;

import java.util.*;

public class Linux {
    public static void main(String[] args) {

        // 使用栈进行 pwd
        Scanner sc = new Scanner(System.in);
        int time = 1;
        int n = sc.nextInt();
        Deque<String> stack = new ArrayDeque<>();
        //stack.add("/");// 添加根目录

        while (n >= time){
            String[] order = sc.nextLine().split("\\s+");

            if(stack.isEmpty()){
                // 如果栈空了
                if("cd".equals(order[0])){
                    if("..".equals(order[1])){
                        // cd .. 出栈
                        System.out.println("/");
                    }else {
                        // cd x 入栈
                        stack.addFirst("/" + order[1]);
                        System.out.println(stack.peekFirst());
                    }
                }
            }else {
                // 如果栈不空
                if("cd".equals(order[0])){
                    if("..".equals(order[1])){
                        // cd .. 出栈
                        stack.removeFirst();
                        System.out.println(stack.peekFirst()); // 栈顶元素
                    }else {
                        // cd x 入栈
                        stack.addFirst("/" + order[1]);
                        System.out.println(stack.peekFirst()); // 栈顶元素
                    }
                }
            }

            // 遇到 pwd,遍历
            StringBuffer sb = new StringBuffer();
            if ("pwd".equals(order[0])){
                for (String s : stack){
                    sb.append(s);
                }
                sb.reverse().substring(0, sb.length());
                String s = sb.substring(0, sb.length() - 1);
                System.out.println("/" + s);
            }
            time++;
        }
    }
}


#携程笔试##携程##java工程师##笔经#
全部评论
兄弟三道全a了吗,用时多久
点赞 回复 分享
发布于 2021-09-11 18:58

相关推荐

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