71.Simplify Path
2016-10-16 11:45
141 查看
题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
思路:
1、边界情况:如果只输入'/':直接返回"/"即可
2、做这道题需要了解linux系统下的绝对路径与相对路径的关系:
(1)相对路径中的 '.' 表示该路径,不进行上下层路径的转换,可以忽略
(2)相对路径中的 '..' 表示当前路径的上一层,比如/ab/cd/.. ,即返回/ab
3、首先想到用栈,然后考虑,是在读取path时处理相对路径,还是从栈中取值时处理。
因为用后者的话,比如遇到/../..这种情况,无法处理。所以选第一种方案。
4、具体处理方案:遇到'/', 入栈;遇到"."或者""时,跳过;遇到"..",跳过并进行出栈
代码:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
思路:
1、边界情况:如果只输入'/':直接返回"/"即可
2、做这道题需要了解linux系统下的绝对路径与相对路径的关系:
(1)相对路径中的 '.' 表示该路径,不进行上下层路径的转换,可以忽略
(2)相对路径中的 '..' 表示当前路径的上一层,比如/ab/cd/.. ,即返回/ab
3、首先想到用栈,然后考虑,是在读取path时处理相对路径,还是从栈中取值时处理。
因为用后者的话,比如遇到/../..这种情况,无法处理。所以选第一种方案。
4、具体处理方案:遇到'/', 入栈;遇到"."或者""时,跳过;遇到"..",跳过并进行出栈
代码:
string simplifyPath(string path) { if (path == "/") return "/"; if (path[path.size() - 1] != '/') path += '/'; stack<string> s; string temp,dst; for (int i = 0; i< path.size(); i++){ if (path[i] != '/') temp += path[i]; else{ if (temp == "." || temp == ""){} else if (temp == ".."){ if (!s.empty()) s.pop(); }else s.push(temp); temp = ""; } } while (!s.empty()){ dst = "/" + s.top() + dst; s.pop(); } if (dst == "") return "/"; else return dst; }
相关文章推荐
- leetCode 71.Simplify Path(化简路径) 解题思路和方法
- leetcode facebook面试题71.Simplify Path
- [leetcode] 71.Simplify Path
- 71.Simplify Path
- 71.Simplify Path
- [leetcode] 71.Simplify Path
- python 系统学习笔记(十二)---os os.path os.walk
- getPath(), getAbsolutePath()和 getCanonicalPath() 的区别
- 124. Binary Tree Maximum Path Sum
- AS-package name does not correspond to the file path
- no acceptable C compiler found in $PATH 解决办法
- ROS中最重要的变量$ROS_PACKAGE_PATH
- file.getPath() getAbsolutePath() getCanonicalPath()区别
- Simplify Path leetcode java
- 11g direct path read介绍:10949 event、_small_table_threshold与_serial_direct_read
- 解决 pathForResource 返回 nil的问题
- Java NIO Path
- System group container for systemgroup.com.apple.configurationprofiles path is
- multipathd: sdn: readsector0 checker reports path is down 多路径出错问题解决
- 1011. Find the external path length