Problem :
Given a string A representing an absolute path for a file (Unix-style).
Return the string A after simplifying the absolute path.
Note:
Absolute path always begin with ’/’ ( root directory ).
Path will not have whitespace characters.
Solution :
string Solution::simplifyPath(string A) {
int l = A.length();
stack<string>s;
string dir = "";
string res;
res.append("/");
for(int i = 0;i<l;i++){
dir = "";
// ignore all slashes
while( i < l && A[i]=='/')i++;
// store dirname in dir
while(i < l && A[i]!='/'){
dir.push_back(A[i]);
i++;
}
// dir == . , continue
if(dir.compare(".") == 0)continue;
// dir == .. , pop() , only if stack is not empty
else if(dir.compare("..") == 0){
if(!s.empty()){
s.pop();
}
}
// if dir != "" then store the dirname in stack
else if(dir != ""){
s.push(dir);
}
}
// stack s , reverse s => rs
stack<string>rs;
while(!s.empty()){
string t = s.top();
rs.push(t);
s.pop();
}
// pop element rs and store it res
while(!rs.empty()){
string t = rs.top();
if(rs.size() == 1){
res.append(t);
}else{
res.append(t+"/");
}
rs.pop();
}
return res;
}
No comments:
Post a Comment