您的位置:首页 > 编程语言 > C语言/C++

[leetcode] 【字符串】71. Simplify Path

2016-06-15 16:50 357 查看
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"
.

题意

简化unix风格的绝对路径

题解

有几种情况需要处理   一是多个/只当1个/处理

二是..表示进入父目录

用一个栈结构存储目录路径的每个文件夹,遇到..则出栈

class Solution {
public:
string simplifyPath(string path) {
stack<string> file;
for(int i=0;i<path.size();)
{
while(path[i]=='/'&&i<path.size())
i++;
string temp;
while(path[i]!='/'&&i<path.size())
temp+=path[i++];
if(temp==".."&&!file.empty())
file.pop();
if(temp!="."&&temp!=".."&&temp!="")
file.push(temp);
}
string res;
if(file.empty())
res="/";
while(!file.empty())
{
res=file.top()+res;
res='/'+res;
file.pop();
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp