首页 > 代码库 > 【LeetCode】Simplify Path
【LeetCode】Simplify Path
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
click to show corner cases.
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"
.
核心在于编写一个split函数以及用进出栈来保存最简路径。
class Solution { public: // true if the argument is slash, false otherwise static bool is_slash(char c) { return (c==‘/‘); } // false if the argument is slash, true otherwise static bool not_slash(char c) { return !is_slash(c); } vector<string> split(const string& str) { typedef string::const_iterator iter; vector<string> ret; iter i = str.begin(); while (i != str.end()) { // ignore leading slashes i = find_if(i, str.end(), not_slash); // find end of next word iter j = find_if(i, str.end(), is_slash); // copy the characters in [i, j) if (i != str.end()) ret.push_back(string(i, j)); i = j; } return ret; } string simplifyPath(string path) { stack<string> pstack; vector<string> pv = split(path); for(vector<string>::size_type st = 0; st < pv.size(); st ++) { if(pv[st] == "..") { if(!pstack.empty()) pstack.pop(); } else if(pv[st] != ".") pstack.push(pv[st]); } string output = ""; if(pstack.empty()) { output = "/"; return output; } while(!pstack.empty()) { output = "/" + pstack.top() + output; pstack.pop(); } return output; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。