leetcode - 71.Simplify Path

    xiaoxiao2021-03-25  74

    Simplify Path

    Given an absolute path for a file (Unix-style), simplify it.

    For example,

    path = "/home/", => "/home"

    path = "/a/./b/../../c/", => "/c"

    Solution:

    public String simplifyPath(String path) { LinkedList<String> list = new LinkedList<>(); Set<String> skip = new HashSet<>(Arrays.asList("..", ".", "")); for (String dir : path.split("/")) { if (dir.equals("..") && !list.isEmpty()) { list.removeLast(); } else if (!skip.contains(dir)) { list.add(dir); } } String result = ""; for (String dir : list) { result += "/" + dir; } return result.isEmpty() ? "/" : result; }
    转载请注明原文地址: https://ju.6miu.com/read-40719.html

    最新回复(0)