首页 > 代码库 > Leetcode Simplify Path
Leetcode Simplify Path
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"
.
题目不难,主要考虑一些特殊情况。
对于path = "/a/./b/../../c/"
, => "/c",模拟一下
先按照‘/‘对字符串进行分割,得到 [a, . , b, .. , .. , c]
首先进入目录a,注意 ‘.‘ 代表当前目录 ,".."代表上一个目录
然后到达‘.‘,还是在当前目录,/a
然后到达‘b‘,这为/a/b
然后到达‘..‘,这是回到父目录,则变为/a
然后到达‘..‘,继续回到父目录,则变为/
然后到达‘c‘,则达到子目录,变为/c
class Solution {public: vector<string> split(string& path, char ch){ int index = 0; vector<string> res; while(index < path.length()){ while(index < path.length() && path[index] == ‘/‘) index++; if(index >= path.length()) break; int start=index, len = 0; while(index < path.length() && path[index]!=‘/‘) {index++;len++;} res.push_back(path.substr(start,len)); } return res; } string simplifyPath(string path) { vector<string> a = split(path,‘/‘); vector<string> file; for(int i = 0 ; i < a.size(); ++ i){ if(a[i] == ".." ){ if(!file.empty()) file.pop_back(); } else if(a[i]!=".") file.push_back(a[i]); } string res=""; if(file.empty()) res ="/"; else{ for(int i = 0 ; i < file.size(); ++ i) res+="/"+file[i]; } return res; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。