题目链接https://oj.leetcode.com/problems/simplify-path/
Description
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的特性,可以得出一个流程图,写代码之前划了,弄上来挺麻烦的,就先这么着吧,有这么几种可能性:(以/a/.b/../../c/为例)
1. 根目录是/,到了根目录..还是这个位置
2. 有文件名就能进入这个目录,所以输入a,得到的现在目录为/a/
3. 一个点等于没点,无效的,文件夹名中有点的情况需要再分析;
4. 非根目录中..代表上一级目录;
简单一分析,你就看到了,这里做的是栈操作,后进先出,结果就是栈内元素。
AC代码
https://oj.leetcode.com/submissions/detail/8709406/
关键词
string, stack, regular