71. 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"
.
解题思路:
我一开始想的是可以以‘/’作为分隔符来读取字符串,但是没有什么合适的方法。
这里需要注意的是:
/..:返回上级目录,所以需要删掉前一个目录名
/. :当前目录
代码:
class Solution { public: string simplifyPath(string path) { string ret, temp; stringstream ss(path); vector<string> p; while(getline(ss, temp, '/')){ if(temp == "" || temp==".") continue; if(temp == ".." && !p.empty()) p.pop_back(); else if(temp != "..") p.push_back(temp); } for(string str : p){ ret += "/" + str; } return ret.empty() ? "/" : ret; } };