美文网首页
LeetCode每日一题:simplify path

LeetCode每日一题:simplify path

作者: yoshino | 来源:发表于2017-05-25 15:17 被阅读19次

问题描述

Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/", =>"/home"
path ="/a/./b/../../c/", =>"/c"
click to show corner cases.
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下的文件路径,包括多余斜杠的去除,当前目录(./)的去除,以及父目录(../)的替代。
这题最好使用队列,先split,忽略””和”.”,处理好“..”就行了

代码实现

public String simplifyPath(String path) {
        LinkedList<String> queue = new LinkedList<>();
        StringBuilder result = new StringBuilder();
        String[] str = path.split("/");
        for (int i = 0; i < str.length; i++) {
            if (str[i].equals("") || str[i].equals(".")) continue;
            if (str[i].equals("..")) {
                if (queue.isEmpty() == false) {
                    queue.pollLast();
                }
            } else queue.add(str[i]);
        }
        while (queue.isEmpty() == false) {
            result.append("/");
            result.append(queue.pollFirst());
        }
        if (result.length() == 0) return "/";
        return result.toString();
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:simplify path

      本文链接:https://www.haomeiwen.com/subject/hfkzxxtx.html