模拟目录管理 - 华为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()

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

相关推荐
秋夫人11 分钟前
B+树(B+TREE)索引
数据结构·算法
kinlon.liu12 分钟前
零信任安全架构--持续验证
java·安全·安全架构·mfa·持续验证
鸽芷咕28 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
王哲晓33 分钟前
Linux通过yum安装Docker
java·linux·docker
java66666888838 分钟前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存39 分钟前
源码分析:LinkedList
java·开发语言
子午39 分钟前
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
人工智能·python·cnn
执键行天涯39 分钟前
【经验帖】JAVA中同方法,两次调用Mybatis,一次更新,一次查询,同一事务,第一次修改对第二次的可见性如何
java·数据库·mybatis
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
风等雨归期1 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序