Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Last active January 24, 2020 12:40
Show Gist options
  • Save adamkorg/36adeab8156778d3852c37a57fb250aa to your computer and use it in GitHub Desktop.
Save adamkorg/36adeab8156778d3852c37a57fb250aa to your computer and use it in GitHub Desktop.
Leetcode 71: Simplify Path
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string simplifyPath(string path) {
vector<string> segs;
string seg;
int prevSlash = -1;
for (int i=0; i<path.size(); ++i) {
if (path[i] == '/' && prevSlash == i-1) {
prevSlash = i;
continue;
}
else if ((path[i] == '/' && prevSlash < i-1) || (i==path.size()-1 && path[i]!='/')) {
int len = (path[i]=='/' ? i-prevSlash-1 : i-prevSlash);
seg = path.substr(prevSlash+1, len);
if (seg == ".") {}
else if (seg == "..") {
if (segs.size() > 0) segs.pop_back();
}
else
segs.push_back(seg);
prevSlash = i;
}
}
string res = "/";
for (int i=0; i<segs.size(); ++i) {
res += segs[i];
if (i != segs.size() - 1) res += "/";
}
return res;
}
int main() {
string path = "/.././GVzvE/./xBjU///../..///././//////T/../../.././zu/q/e"; //"/..."; //"/a//b////c/d//././/.."; //"/a/../../b/../c//.//"; //"/home//foo/"; //"/../"; //"/home/";
cout << simplifyPath(path) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment