企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一.题目描述 Given an absolute path for a file (Unix-style), simplify it.  For example,  path = “/home/”, => “/home”  path = “/a/./b/../../c/”, => “/c” Corner Cases:  • Did you consider the case where path = “/../”? In this case, you should return “/”. • Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”. In this case, you should ignore redundant slashes and return “/home/foo”. ## 二.题目分析 简化一个Unix风格下的文件路径。例如输入代表路径的字符串:”/home/”,简化后为:”/home”;或输入”/a/./b/../../c/”,简化为:”/c” 字符串中,应该了解到”..”是返回到路径的上级目录(如果当前根目录则不处理),这里使用栈来记录路径名。在处理字符串的过程中,有以下条件: ~~~ 1\. 重复连续出现的'/',只按1个处理,即跳过重复连续出现的'/'; 2\. 如果路径名不为"."和"..",将记录的字符串入栈; 3\. 如果路径名是".."且栈不为空,则需要出栈,否则无需处理; ~~~ 在遍历字符串后,逐个取出栈中元素(即已保存的路径名),用’/’分隔并拼接起来,注意取出的元素是从后往前连接的。 ## 三.实例代码 ~~~ #include <iostream> #include <stack> #include <string> using namespace std; class Solution { public: string simplifyPath(string path) { stack<string> str; for (size_t i = 0; i < path.size(); ++i) { string name = ""; while (i < path.size() && path[i] == '/') ++i; // 该操作跳过斜线'/' while (i < path.size() && path[i] != '/') name += path[i++]; // 开始记录路径名,包括".." if (name != "." && name != "..") // 对对不同的文件名进行不同操作 str.push(name); // 非".."文件名,压栈 else if (!str.empty() && name == "..") str.pop(); // 当前文件名为"..",表示退到上层目录,需弹出栈 } if (str.empty()) return "/"; string result = ""; while (!str.empty()) { result = "/" + str.top() + result; // 最后组合path str.pop(); } return result; } }; ~~~ ![](https://box.kancloud.cn/2016-01-05_568bb5ee4aabb.jpg) ## 四.小结 这道题使用了string类的一些操作,该类的一些功能确实非常强大。以下是关于string类的一些用法总结:  [http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html](http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html)