leetcode-Simplify Path
2015-06-19 09:23
441 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
class Solution {
public:
string simplifyPath(string path) {
int i = 0;
stack<string> s;
stack<string> ans;
string temp = "";
int flag = 0;
for(i = 0;i<path.length();i++)
{
if(path[i] == '/' && flag == 0)//开始一个文件夹
{
temp = "";
flag = 1;
}
else if(path[i] == '/' && flag == 2)//结束一个文件夹
{
if(temp == ".")
{
flag = 0;
i--;
continue;
}
else if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
{
s.push(temp);
}
flag = 0;
i--;
}
else if((flag == 1 || flag == 2)&& path[i] != '/' )//文件夹的名字
{
temp = temp + path[i];
flag = 2;
}
}
/*最后一个文件夹*/
if(flag == 2)
{
if(temp != ".")
{
if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
s.push(temp);
}
}
while(!s.empty())/*目录正序输出*/
{
ans.push(s.top());
s.pop();
}
string direction = "/";//最终简化目录
while(ans.size()!=0)
{
direction = direction + ans.top();
if(ans.size() != 1)
direction = direction + "/";
ans.pop();
}
return direction;
}
};
For example,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
思路:取得每个 文件夹名称,针对“..” 和 "."的情况通过栈进行存储更新;最后目录输出还要有一个栈用于文件夹名称顺序颠倒;
class Solution {
public:
string simplifyPath(string path) {
int i = 0;
stack<string> s;
stack<string> ans;
string temp = "";
int flag = 0;
for(i = 0;i<path.length();i++)
{
if(path[i] == '/' && flag == 0)//开始一个文件夹
{
temp = "";
flag = 1;
}
else if(path[i] == '/' && flag == 2)//结束一个文件夹
{
if(temp == ".")
{
flag = 0;
i--;
continue;
}
else if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
{
s.push(temp);
}
flag = 0;
i--;
}
else if((flag == 1 || flag == 2)&& path[i] != '/' )//文件夹的名字
{
temp = temp + path[i];
flag = 2;
}
}
/*最后一个文件夹*/
if(flag == 2)
{
if(temp != ".")
{
if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
s.push(temp);
}
}
while(!s.empty())/*目录正序输出*/
{
ans.push(s.top());
s.pop();
}
string direction = "/";//最终简化目录
while(ans.size()!=0)
{
direction = direction + ans.top();
if(ans.size() != 1)
direction = direction + "/";
ans.pop();
}
return direction;
}
};
相关文章推荐
- DOS配合FastCopy实现远程增量备份
- xml的概念及说明
- 运行 测试
- 节省空间交换变量基本算法
- 为Angular-UEditor增加工具栏属性
- 内部排序(三)选择排序
- JavaScript中数据结构与算法(一):栈
- Partition List
- AudioServicesPlaySystemSound音频服务—IOS开发
- Super BOM应用步骤总结
- spring mvc 采用 jsr303 bean validation 校验框架
- sql server链接服务器增加mysql
- MySQL数据库在实际应用一些方面的介绍
- android自动登录
- C#如何获取本地IP地址(仅限于单网卡)
- 工厂方法模式与抽象工厂模式
- Error inflating class and android.support.v7.widget.CardView
- 《Storm入门》中文版
- 基于BRDF的光照模型
- 修改MS SQL忽略大小写