Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 28, 2013 13:44
Show Gist options
  • Select an option

  • Save pdu/4655597 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4655597 to your computer and use it in GitHub Desktop.
Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" http://leetcode.com/onlinejudge#question_71
void update(vector<string>& s, const string& t) {
if (t == ".")
;
else if (t == "..") {
if (!s.empty())
s.pop_back();
}
else
s.push_back(t);
}
class Solution {
public:
string simplifyPath(string path) {
vector<string> s;
int prev = -1;
for (int i = 0; i < path.length(); ++i)
if (path[i] == '/') {
if (prev != -1 && prev != i)
update(s, path.substr(prev, i - prev));
prev = i + 1;
}
if (prev != path.length())
update(s, path.substr(prev, path.length() - prev));
if (s.empty())
return "/";
string ret;
for (int i = 0; i < s.size(); ++i)
ret.append("/").append(s[i]);
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment