Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
Corner Cases:
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".
刚看题时不太了解题目意思,毕竟不懂Unix-style。这题要求是:
1,用斜线/ 分割出来的字符串,如果是”.” ,不做操作
2,如果是“..”,则把之前的一个字符串删除,如“/b/../c”,操作后变成“/c”。
3,如果路径中出现“//”,则和谐掉一个。
解法:建立一个栈存放用“/”分割出来的字符串,当遇到“..”若栈不为空,则把栈顶元素出栈。
class Solution {
public:
string simplifyPath(string path) {
string ans;
stack<string> stk;
int n=path.size();
for(int i=0;i<n;i++){
if(path[i]=='/'){
string temp;
for(int j=i+1;j<n;j++){
if(path[j]!='/')temp+=path[j];//用temp来保存两个//中间的字符串
else {i=j-1;break;}//如果path[j]=='/',则跳出内循环
}
if(temp=="")continue;//表示路径中出现"//"
if(temp==".."){
if(!stk.empty())stk.pop();
}
else if(temp=="."){}//不做任何操作
else stk.push(temp);//是其他字符串就入栈
}
}
while(!stk.empty()){
ans="/"+stk.top()+ans;//由于栈是先进后出,那么一层层出栈,加在ans前面
stk.pop();
}
if(ans.size()==0)return "/";
return ans;
}
};