欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 79:simplify path

发布时间:2025/4/14 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 79:simplify path 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

本题简单来说 就是字符串的处理 同时要有相关的情况分类 比如当前目录 父目录 多个斜线等

但其实 就父目录时需要回到上一路经 当前目录时不做任何变化 其他目录时需要进入其他目录 这一特征  本题可用栈来存储整个路径寻找的过程

在path中 逐一找到斜线之间的当前路径名 并分类判断 分类处理  使得栈中存储的为路径的一系列名字  最后再反向串起来成路径真正的字符串即可。

class Solution {
public:
    string simplifyPath(string path) {
        string res_path="";
        if (path.size()==0)
            return res_path;
        stack<string> stack_path;
        for (int i=0; i<path.size();)
        {
            while(i<path.size() && path[i]=='/')
                ++i;
            string name="";
            while(i<path.size() && path[i]!='/')
                name += path[i++];
            if (name==".." && !stack_path.empty())
                stack_path.pop();
            else if(name!="" && name!="." && name!="..")
                stack_path.push(name);
        }
        if (stack_path.empty())
            res_path += '/';
        else
        {
            while(!stack_path.empty())
            {
                res_path = '/'+stack_path.top()+res_path;
                stack_path.pop();
            }
        }
        return res_path;
    }
};

转载于:https://www.cnblogs.com/weiyi-mgh/p/6406363.html

总结

以上是生活随笔为你收集整理的leetcode 79:simplify path的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。