您的位置:首页 > 其它

LeetCode 71. Simplify Path

2016-05-08 10:06 288 查看
Given an absolute path for a file (Unix-style), simplify it.

For example,

path =
"/home/"
, =>
"/home"


path =
"/a/./b/../../c/"
, =>
"/c"


Code copied from EPI.


#include <sstream>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
/*
I didn't quite understand this problem.
This is to simply the given linux-like path command.
. stands for current directory.
.. stands for going to parent directory.
*/
string shortestEquivalentPath(const string& path) {
if(path.size() == 0) return "";
vector<string> path_names;
if(path.front() == '/') path_names.push_back("/");
stringstream ss(path);
string token;
while(getline(ss, token, '/')) {
if(token == "..") {
// need to consider the /../../ case. This will be simpiled to ..
if(path_names.empty() || path_names.back() == "..") {
path_names.push_back(token);
} else {
path_names.pop_back();
}
} else if(token != "." && token != "") {
path_names.push_back(token);
}
}
string result;
if(!path_names.empty()) {
result = path_names.front();
for(int i = 1; i < path_names.size(); ++i) {
if(i == 1 && result == "/") { // to in case of starting with "//"
result += path_names[i];
} else {
result += '/' + path_names[i];
}
}
} else result = "/";
return result;
}
int main(void) {
  cout << shortestEquivalentPath("/home/") << endl;
  cout << shortestEquivalentPath("/a/./b/../../c/") << endl;
  cout << shortestEquivalentPath("/../../") << endl;
  cout << shortestEquivalentPath("//foo/") << endl;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: