我是靠谱客的博主 酷炫奇异果,最近开发中收集的这篇文章主要介绍算法:Unix是如何简化路径的Simplify Path简化路径规则题目Stack解法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period … moves the directory up a level.

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

Input: "/a//bc/d//././/.."
Output: "/a/b/c"

Stack解法

这里用到Stack的解法,Duque在这里是双向队列。如果是"…",则从Stack移除上一个,如果不是是空并且不是".", 则加入到Stack中。

class Solution {
    public String simplifyPath(String path) {
        String slash = "/";
        Deque<String> stack = new LinkedList<>();
        for (String s: path.split(slash)) {
          if (s.equals("..")) stack.poll();
          else if (!s.isEmpty() && !s.equals(".")) stack.push(s);
        }

        if (stack.size() == 0) return slash;
        StringBuilder sb = new StringBuilder();
        while (stack.size() != 0) {
          sb.append(slash).append(stack.pollLast());
        }

        return sb.toString();
    }
}

最后

以上就是酷炫奇异果为你收集整理的算法:Unix是如何简化路径的Simplify Path简化路径规则题目Stack解法的全部内容,希望文章能够帮你解决算法:Unix是如何简化路径的Simplify Path简化路径规则题目Stack解法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部