1天1道LeetCode 本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
歡迎轉載,轉載請注明出處
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”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”.
題目大意:給定1個絕對路徑,簡化路徑
注意1下幾點:
1、“..”表示跳到上1層目錄
2、“.”表示當前目錄
3、“////”多個/當1個處理
在這里,我們可以利用stack來處理,“..”則把棧頂元素彈出,“.”則不作處理,其他的表示目錄的名字就直接壓棧。
具體思路可以看代碼:
class Solution {
public:
string simplifyPath(string path) {
stack<string> pathStack;//寄存目錄
path+="/";//避免處理邊界,即/a這類情況
string temp = "";//用作臨時string
for(int i = 0 ; i< path.length() ;)
{
if(path[i] == '/')
{
if(temp=="..") {//返回上1層目錄
if(!pathStack.empty()) pathStack.pop();//如果非空則彈出,為空就不做處理
}
else if(temp=="."|| temp =="") {}//不做處理,當前目錄
else pathStack.push(temp);//正常的目錄
while(i<path.length()&&path[i]=='/') i++;//跳過連續的‘/’
temp = "";//temp初始化
}
else
{
temp+=path[i++];
}
}
string ret;
if(pathStack.empty()) ret = "/";//為空時直接輸出
else {
while(!pathStack.empty())//非空則按格式輸出
{
string eachPath = pathStack.top();
pathStack.pop();
ret = "/"+eachPath + ret;
}
}
return ret;
}
};
上一篇 UML思維導圖