题目:
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period … moves the directory up a level.
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
思路:
用splitString将path字符串切开,切成多个word。然后逐个word处理下就好了。
代码实现:
class Solution {
public:
void splitString(vector<string> &strings, const string &org_string, const string &seq){
string::size_type p1 = 0;
string::size_type p2 = org_string.find(seq);
while (p2 != string::npos){
if (p2 == p1){
++p1;
p2 = org_string.find(seq, p1);
continue;
}
strings.push_back(org_string.substr(p1, p2-p1));
p1 = p2 + seq.size();
p2 = org_string.find(seq, p1);
}
if (p1 != org_string.size()){
strings.push_back(org_string.substr(p1));
}
}
string simplifyPath(string path) {
vector<string> words;
vector<string> ans_vec;
splitString(words, path, "/");
for (int i = 0; i < words.size(); ++i){
if (words[i] == "."){
continue;
}else if(words[i] == ".."){
if (ans_vec.size() > 0){
ans_vec.pop_back();
}
}else{
ans_vec.push_back(words[i]);
}
}
string ans_str;
for (int i = 0; i < ans_vec.size(); ++i){
ans_str += ("/" + ans_vec[i]);
}
if (ans_str == ""){
return "/";
}
return ans_str;
}
};
discuss:
思路:用getline将每一部分切分,然后用stack把路径中每一部分都保存起来,过滤掉符号,最后再重新拼接还原即可。
class Solution {
public:
string simplifyPath(string path) {
string tmp;
vector<string> stk;
stringstream ss(path);
while (getline(ss, tmp, '/')){ // 用getline拆分字符串
if (tmp == "" or tmp == "."){
continue ;
}
if (tmp == ".." and !stk.empty()){
stk.pop_back();
}else if (tmp != ".."){
stk.push_back(tmp);
}
}
string res;
for (auto str : stk){
res += "/" + str;
}
return res.empty() ? "/" : res;
}
};
参考:https://www.cnblogs.com/dfcao/p/cpp-FAQ-split.html评论区egmkang的回答。