71. Simplify Path(M)

71. Simplify Path

复制代码
 1 Given an absolute path for a file (Unix-style), simplify it.
 2 
 3 For example,
 4 path = "/home/", => "/home"
 5 path = "/a/./b/../../c/", => "/c"
 6 click to show corner cases.
 7 
 8 Corner Cases:
 9 Did you consider the case where path = "/../"?
10 In this case, you should return "/".
11 Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
12 In this case, you should ignore redundant slashes and return "/home/foo".
复制代码

 

复制代码
 1 class Solution {
 2 public:
 3      string simplifyPath(string path) {
 4         deque<string> qs;
 5         string result;
 6         int plen = path.size();
 7         string::size_type curindex = 0, lastindex = 0;
 8 
 9         while (lastindex < plen && (curindex = path.find("/", lastindex)) != string::npos)
10         {
11             if(path.find("//", lastindex))
12             {
13                 qs.push_back(path.substr(lastindex, curindex+1-lastindex));
14                 lastindex = curindex+2;
15             }else if (path.find("./", lastindex)) {
16                 lastindex = curindex+1;
17             }else if (path.find(".//", lastindex)) {
18                 lastindex = curindex+2;
19             }else if (path.find("../", lastindex)) {
20                 qs.pop_back(); // go back one step
21                 lastindex = curindex+1;
22             }else if (path.find("..//", lastindex)) {
23                 qs.pop_back();
24                 lastindex = curindex+2;
25             }else {
26                 qs.push_back(path.substr(lastindex, curindex+1-lastindex));
27                 lastindex = curindex+1;
28             }
29         }
30 
31         while (!qs.empty()) {
32             string tmp = qs.front();
33             qs.pop_front();
34             result.append(tmp);
35         }
36         if(result.size() != 1){
37             result.resize(result.size()-1);
38         }
39         return result;
40     }
41 };
View Code
复制代码

 

posted @   PKICA  阅读(170)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2016-09-11 c++ static及const(开发者在线)
2015-09-11 operator new,new operator,placement new的区别
点击右上角即可分享
微信分享提示