Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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"
题目描述的很清楚,这道题的思路也很简单,重点使边界条件的考虑和数据结构的选择,我最初想使用栈,但是后来发现vector更合适。
class Solution{
public:
string simplifyPath(string path){
string res;
if(path.empty()){
return res;
}
vector <string> s;
//Tokenize the path and process the vector
int pos = 0;
int i = path.find('/');
while(i!=string::npos){
//Current dir name
string temp = path.substr(pos,i-pos);
pos = i+1; // Next start Pos
// Deal ..
if(temp.compare("..")==0){
if(!s.empty()){
s.pop_back();
}
}
else{
// If "." and "" do nothing
// Else record the dir name
if(temp.compare(".") != 0&&temp.compare("")!=0){
s.push_back(temp);
}
}
i = path.find('/',pos);
}
//Deal the last Dir name like "/home"
if(pos != path.length()){
string temp = path.substr(pos);
if(temp.compare("..")==0){
if(!s.empty()){
s.pop_back();
}
}
else{
if(temp.compare(".") != 0&&temp.compare("")!=0){
s.push_back(temp);
}
}
}
for(int i=0;i<s.size();i++){
res += "/";
res += s[i];
}
//If the real path is "" then make the res = "/"
if(res.empty()){
res +="/";
}
return res;
}
};