模拟目录管理 - 华为OD统一考试(C卷)

OD统一考试(C卷)

分值: 200分

题解: Java / Python / C++

题目描述

实现一个模拟目录管理功能的软件,输入一个命令序列,输出最后一条命令运行结果。

支持命令:

1)创建目录命令: mkdir 目录名称,如mkdir abc为在当前目录创建abc目录,如果已存在同名目录则不执行任何操作。此命令无输出。

2)进入目录命令: cd 目录名称,如cd abc为进入abc目录,特别地,cd ...为返回上级目录,如果目录不存在则不执行任何操作。此命令无输出。

3)查看当前所在路径命令: pwd,输出当前路径字符串

约束:

1)目录名称仅支持小写字母;mkdir和cd命令的参数仅支持单个目录,如: mkdir bc和cd abc;不支持嵌套路径和绝对路径,如mkdir abc/efg,cd abc/efg,mkdir /abc/efg,cd /abc/efg是不支持的。

2)目录符号为/,根目录/作为初始目录。

输入描述

输入N行字符串,每一行字符串是一条命令。

输出描述

输出最后一条命令运行结果字符串

示例1

复制代码
输入:
mkdir abc
cd abc
pwd

输出:
/abc/

说明:
在根目录创建一个abc的目录并进入abc目录中查看当前目录路径,输出当前路径/abc/。

备注

命令行数限制100行以内,目录名称限制10个字符以内。

题解

解题思路:使用一个File类来表示目录,其中包含目录名称、父目录指针和子目录映射。通过实现mkdir、cd和pwd方法来实现创建目录、进入目录和查看当前路径的功能。在main函数中,根据输入的命令序列执行相应的操作,并输出最后一条命令的运行结果。

代码大致描述:

  1. 定义一个File类,包含name、parent和subFile成员变量。
  2. 实现mkdir方法,用于创建目录。
  3. 实现cd方法,用于进入目录。
  4. 实现pwd方法,用于查看当前路径。
  5. 在main函数中,创建一个根目录对象root,并初始化当前目录cur为root。
  6. 读取输入的命令序列,根据命令执行相应的操作,并更新当前目录cur。
  7. 输出最后一条命令的运行结果。

时间复杂度:O(N),其中N为命令序列的长度。

空间复杂度:O(M),其中M为目录结构的最大深度。

C++

cpp 复制代码
#include <iostream>
#include <unordered_map>
using namespace std;

class File {
public:
    string name;
    File* parent;
    unordered_map<string, File*> subFile;

    File(const string& name) : name(name), parent(nullptr) {}

    void mkdir(const string& dir) {
        if (subFile.find(dir) != subFile.end()) return;

        File* newFile = new File(dir);
        newFile->parent = this;
        subFile[dir] = newFile;
    }

    File* cd(const string& dir) {
        if (dir == "..") {
            if (this->parent != nullptr) return this->parent;
        }

        if (subFile.find(dir) != subFile.end()) return subFile[dir];

        return this;
    }

    void pwd() {
        File* temp = this;
        string path = "/";
        while (temp->parent != nullptr) {
            path = "/" + temp->name + path;
            temp = temp->parent;
        }

        cout << path << endl;
    }
};

int main() {
    File* root = new File("");
    File* cur = root;

    string command;
    while (getline(cin, command)) {
        if (command.find("mkdir") == 0) {
            string dir = command.substr(6);
            cur->mkdir(dir);
        } else if (command.find("cd") == 0) {
            string dir = command.substr(3);
            cur = cur->cd(dir);
        } else {
            cur->pwd();
        }
    }

    return 0;
}

Java

java 复制代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        File root = new File("");
        File cur = root;
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String command = scanner.nextLine();
            if (command.startsWith("mkdir")) {
                String dir = command.split(" ")[1];
                cur.mkdir(dir);
            } else if (command.startsWith("cd")) {
                String dir = command.split(" ")[1];
                cur = cur.cd(dir);
            } else {
                cur.pwd();
            }
        }
    }
}

class File {
    String name;
    File parent;
    Map<String, File> subFile = new HashMap<>();

    public File(String name) {
        this.name = name;
    }

    public void mkdir(String dir) {
        if (subFile.containsKey(dir)) return;

        File newFile = new File(dir);
        newFile.parent = this;
        subFile.put(dir, newFile);
    }

    public File cd(String dir) {
        if ("..".equals(dir)) {
            if (this.parent != null) return this.parent;
        }

        if (subFile.containsKey(dir)) return this.subFile.get(dir);

        return this;
    }

    public void pwd() {
        File temp = this;
        String path = "/";
        while (temp.parent != null) {
            path = "/" + temp.name + path;
            temp = temp.parent;
        }

        System.out.println(path);
    }
}

Python

python 复制代码
import sys

class File:
    def __init__(self, name):
        self.name = name
        self.parent = None
        self.subFile = {}

    def mkdir(self, dir):
        if dir in self.subFile:
            return

        new_file = File(dir)
        new_file.parent = self
        self.subFile[dir] = new_file

    def cd(self, dir):
        if dir == "..":
            if self.parent:
                return self.parent

        if dir in self.subFile:
            return self.subFile[dir]

        return self

    def pwd(self):
        temp = self
        path = "/"
        while temp.parent:
            path = "/" + temp.name + path
            temp = temp.parent

        print(path)


if __name__ == "__main__":
    root = File("")
    cur = root

    for command in sys.stdin:
        if command.startswith("mkdir"):
            directory = command.split()[1]
            cur.mkdir(directory)
        elif command.startswith("cd"):
            directory = command.split()[1]
            cur = cur.cd(directory)
        else:
            cur.pwd()

🙏整理题解不易, 如果有帮助到您,请给点个赞 ‍❤️‍ 和收藏 ⭐,让更多的人看到。🙏🙏🙏

相关推荐
涛声依旧-底层原理研究所14 分钟前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
一只大袋鼠14 分钟前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet20 分钟前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch43 分钟前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆43 分钟前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
web3.08889991 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
德思特1 小时前
从 Dify 配置页理解 RAG 的重要参数
java·人工智能·llm·dify·rag
张小姐的猫1 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
YOU OU1 小时前
Spring IoC&DI
java·数据库·spring