Description:
Given an absolute path for a file (Unix-style), simplify it.
Note:
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Solution:
Analysis and Thinking:
問題要求對輸入的文件的絕對路徑進行簡化,並輸出簡化的路徑結果。觀察發現這是unix風格的文件路徑命名,其重點是對字符串的處理,特別對“..”這一表示上級目錄的符號的處理,本文利用了棧結構來處理,用棧來記錄文件路徑名,並對處理到的字符串是/或.或..或其他字符,做相應的處理。
Steps:
1.構建棧用於記錄輸入的文件路徑名
2.遍歷路徑名,如果當前字符是'/',則不處理,跳至下一個字符
3.如果不是/,用一變量s存儲字符子串,知道下一個'/'的出現
4.判斷s是否爲“..”,如果是,且當前路徑棧不爲空,則彈棧
5.如果s不爲“”、“.”、".."三者之一,則將其入棧,如果文件路徑還沒遍歷完,跳回2
6.將棧內元素彈出,並用一結果數組記錄鏈接,返回結果數組
Codes:
class Solution
{
public:
string simplifyPath(string path)
{
stack<string> pathRecoder;
for(int i=0;i<path.size();)
{
while(path[i]=='/'&&i<path.size())
{
i++;
}
string tempStr="";
while(path[i]!='/'&&i<path.size())
{
tempStr=tempStr+path[i++];
}
if(tempStr==".."&&tempStr.empty())
pathRecoder.pop();
else if(tempStr!=""&&tempStr!="."&&tempStr!="..")
pathRecoder.push(tempStr);
}
string result="";
if(pathRecoder.empty())
{
return"/";
}
while(!pathRecoder.empty())
{
result="/"+result+pathRecoder.top();
pathRecoder.pop();
}
return result;
}
};
Results: