leetcode71. Simplify Path

来源:互联网 发布:上海大学网络选课 编辑:程序博客网 时间:2024/05/16 01:08

71. Simplify Path

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

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

解法

如果非’.’ ‘..’ ”的元素入栈,如果是..元素出栈,如果是’.’或者”,不予处理。最终遍历栈,栈底的元素是根目录下的第一个目录。

public class Solution {    public String simplifyPath(String path) {        if (path == null || path.length() == 0) {            return null;        }        Stack<String> stack = new Stack<>();        List<String> list = Arrays.asList("..", ".", "");        String[] dirs = path.split("/");        for (String dir : dirs) {            if (dir.equals("..") && !stack.isEmpty()) {                stack.pop();            }            else if (!list.contains(dir)) {                stack.push(dir);            }        }        String res = "";        while (!stack.empty()) {            res = "/" + stack.pop() + res;        }        return res.isEmpty() ? "/" : res;    }}

这里写图片描述

0 0
原创粉丝点击