首页 > 试题广场 >

简化路径

[编程题]简化路径
  • 热度指数:9654 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请简化给出的Unix样式的文件绝对路径,也就是转换成规范路径
在Unix样式的文件系统中, .代表当前目录,.. 表示将目录向上移动一级,更多的介绍可以查看 Absolute path vs relative path in Linux/Unix
请注意,返回的规范路径必须以斜杠“/”开头,并且两个目录名之间只能有一个斜杠“/”开头。如果存在的最后一级目录的话不能以“/”结尾。另外,转化出的规范路径必须是能表示给出的绝对路径的最短字符串。
例如:
文件路径 = "/web/", =>"/web"
文件路径 = "/a/./b/../../c/", =>"/c"
特殊样例:
  • 你有考虑过样例 文件路径 ="/../"吗? 这个样例应该返回"/".
  • 另一种特殊样例是路径中可能相邻的有多个“/”,例如“/home//web/”。这种情况下应该忽略多余的“/”,这个样例应该返回"/home/web".
示例1

输入

"/./"

输出

"/"
示例2

输入

"/.."

输出

"/"
示例3

输入

"/..."

输出

"/..."
import java.util.*;

public class Solution {
    public String simplifyPath(String path) {
        if (path == null) {
            return "/";
        }
        String[] subStrs = path.split("/");
        List<String> res = new ArrayList();
        for (int i = 0;i < subStrs.length;i++) {
            if (subStrs[i].equals("") || subStrs[i].equals(".")) {
                continue;
            } else if (subStrs[i].equals("..")) {
                if (!res.isEmpty()) {
                    res.remove(res.size() - 1);
                }
            } else {
                res.add(subStrs[i]);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String s : res) {
            sb.append("/");
            sb.append(s);
        }
        return sb.toString().isEmpty() ? "/" : sb.toString();
    }
}

编辑于 2019-11-03 18:51:01 回复(0)
public String simplifyPath(String path) {
        Stack<String> input = new Stack<>();
        Stack<String> result = new Stack<>();
        String[] split = path.split("/");
        
        for(String s : split) if(s.length() > 0) input.push(s);    
        for(String s : input){
            if(s.equals("..")) {
                if(!result.isEmpty()) result.pop();
            }
            else if(s.equals(".")) continue;
            else result.push(s);
        }
        
        return "/" + String.join("/", result);
    }
input栈存放/之间合法的路径名,包括..和.
result栈存放识别..和.后最终的输出结果
总结:String的split()方法和join()方法能大幅简化代码,前后元素相互影响的情况下可以考虑使用栈
发表于 2019-05-18 10:59:40 回复(0)

The main idea is to push to the stack every valid file name (not in {"",".",".."}), popping only if there's smth to pop and we met "..". I don't feel like the code below needs any additional comments.

public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>(); Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));
    for (String dir : path.split("/")) { if (dir.equals("..") && !stack.isEmpty()) stack.pop(); else if (!skip.contains(dir)) stack.push(dir);
    } String res = "";
    for (String dir : stack) res = "/" + dir + res; return res.isEmpty() ? "/" : res;
}
发表于 2017-03-12 12:05:09 回复(0)