leetcode【第十二周】简化路径
来源:互联网 发布:linux服务器ftp服务开 编辑:程序博客网 时间:2024/06/15 14:36
问题描述:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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系统下路径转化的问题,把有复杂相对路径转化为简单直接的绝对路径。可以通过字符是否是"/"来记录和移动下标,从而逐段逐段地截取输入路径的内容。同样,我们知道,对于文件的访问类似于一个栈的结构,当读到一个目录名就进展,遇到“..”就是回退到上一级目录,就是说将当前顶部的文件名出栈。因为我们可以对我们逐段截取到的字符串来做判断,若是“.”,则不做处理,若不等于“..”则是文件夹名,将它入栈【这里我们采用一个字符串数组来存放】,若是"..",则将栈顶元素出栈,相当于返回一级目录。一次类推,即可得到正确且简洁的文件夹访问顺序。当输出路径时,若栈中无文件夹名存在【即在当前目录】,则返回“/”。具体的实现代码如下。
代码如下:
class Solution {public:string simplifyPath(string path) {vectortmp;int index = 0;while (index < path.length()-1){while (path[index] == '/'&&index < path.length())index++;int start = index;while (path[index] != '/'&&index < path.length())index++;int end = index-1;string con = path.substr(start,end-start+1);cout << con << endl;if (con == ".."){if (!tmp.empty())tmp.pop_back();}else if (con != "."){tmp.push_back(con);}}string res;for (vector ::iterator iter = tmp.begin(); iter != tmp.end(); iter++){if (*iter != "\0"){res += "/";res += *iter;}}if(res=="") return "/";else return res;}};
0 0
- leetcode【第十二周】简化路径
- Simplify Path 简化文件路径@LeetCode
- [LeetCode]—Simplify Path 简化路径表达式
- LeetCode:简化路径(Simplify Path)
- LeetCode 71. Simplify Path(简化路径)
- LeetCode-----71. Simplify Path(简化文件路径)
- 【Leetcode】71 Simplify path 简化路径
- leetcode-python 第十二周
- leetcode-第十二周
- 第十二周leetcode题
- 第十二周LeetCode
- 第十二周LeetCode
- 第十二周LeetCode
- LeetCode题解 第十二周
- 简化路径
- 简化路径
- 简化路径
- 第十二周项目四:银行系统简化版
- 实现一个通讯录; 通讯录可以用来存储1000个人的信息,每个人的信息包括: 姓名、性别、年龄、电话、住址 提供方法: 1. 添加联系人信息 2. 删除指定联系人信息 3. 查找指定
- codeforces 791B
- Composer 学习笔记
- 希尔排序之Java实现
- 每天学一点Swift——Swift简介以及Xcode入门使用
- leetcode【第十二周】简化路径
- TP3.2.3从入门到放弃-使用TP开发项目-1
- 连续子数组的最大和 java
- 【Unity3d】 导出IOS锁屏闪退
- Python学习笔记
- ThinkPHP5之多语言切换
- 二叉树的前序,中序,后序的递归与非递归遍历
- C++第6次作业
- 联合体,位域, 结构体对齐