`

Leetcode - Simplify Path

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

[分析] 思路很简单,遇到“.”跳过,遇到“..”删除其前面一级目录,使用堆栈来删除前一级目录的想法很妙(要是我自己想出来就好了~)。 另外分割字符串来处理的思路也要用心体会,联系reverse-words-in-a-string 一题:
https://leetcode.com/problems/reverse-words-in-a-string/

    public String simplifyPath(String path) {
        if (path == null || path.length() == 0)
            return path;
        String[] dirs = path.split("/");
        LinkedList<String> stack = new LinkedList<String>();
        for (String dir : dirs) {
            if (dir.isEmpty() || dir.equals("."))
                continue;
            else if (dir.equals("..")) {
                if (!stack.isEmpty())
                    stack.pop();
            } else {
                stack.push(dir);
            }
        }
        if (stack.isEmpty()) {
            return "/";
        }
        StringBuilder newpath = new StringBuilder();
        while (!stack.isEmpty()) {
            newpath.insert(0,"/" + stack.pop());
        }
        return newpath.toString();
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics