【Simplify Path】cpp
题目:
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"
.
代码:
class Solution { public: string simplifyPath(string path) { string result = ""; path.append("/"); // some input path not end with "/" vector<string> ret; // use vector acting as stack string tmp_part = ""; ret.push_back(string(1,path[0])); for ( size_t i = 1; i < path.size(); ++i ){ if ( path[i]=='/' ){ if ( tmp_part==".." ){ if ( ret.size()>1 ) { ret.erase(ret.end()-1); ret.erase(ret.end()-1); } } else { if ( tmp_part!="" && tmp_part!="." ) { ret.push_back(tmp_part); ret.push_back("/"); } } tmp_part = ""; } else { tmp_part += path[i]; } } if ( ret.size()>1 && ret[ret.size()-1]=="/" ) ret.erase(ret.end()-1); for ( size_t i = 0; i < ret.size(); ++i ) result += ret[i]; return result; } };
tips:
主要思想是stack堆栈的数据结构。
1. 利用"/"来作为间隔判断符号
2. tmp_part为两个"/"之间的字符串部分(需要注意输入的path可能不以"/"结尾,解决办法是人工在path后面补上一个)
3. 如果tmp_part为“..”,则出栈两个元素(前提是栈中元素数目足够)
如果tmp_part不为“.”, 且不为".",且不为"", 则入栈(注意,还要包括后面的“/”)
其他部分靠题目提供的一些corner cases来debug了。
这里用到的一个技巧是vector来代替stack;这样做的好处是返回结果时不用将stack的元素倒序组合。
===============================================
第二次过这道题,大体路子还清晰。有一个地方没有考虑周全:从for退出来时,不能默认最后一个元素直接进栈,需要判断最后一个元素是否合规。
还有,用到stack的,进栈最好检查一下是否符合规定,不符合规定,直接往外弹元素。
class Solution { public: string simplifyPath(string path) { stack<string> sta; int begin = 0; int len = 0; for ( int i=0; i<path.size(); ++i ) { if ( path[i]!='/' ){ len++; } else{ if ( len!=0 ) { string tmp = path.substr(begin,len); if (tmp==".") {} else if ( tmp==".." ) { if (!sta.empty()) sta.pop(); } else { sta.push(path.substr(begin,len)); } } begin = i+1; len = 0; } } if ( begin<path.size() ) { if ( len!=0 ) { string tmp = path.substr(begin,len); if (tmp==".") {} else if ( tmp==".." ) { if (!sta.empty()) sta.pop(); } else { sta.push(path.substr(begin,len)); } } } string ret = ""; if (sta.empty()) return "/"; while ( !sta.empty() ) { ret = "/" + sta.top() + ret; sta.pop(); } return ret; } };
分类:
cpp刷Leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?