Leetcode Simplify Path

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode Simplify Path相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/simplify-path/

题目:

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

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

思路:

easy

算法

public String simplifyPath(String path) {  
        String s[] = path.trim().split("\\\\/+");  
        Stack<String> stack = new Stack<String>();  
  
        for (String str : s) {  
            if (!str.equals("") && !str.equals(" ") && !str.equals(".") && !str.equals("..")) {  
                stack.push(str);  
            } else if (str.equals("..") && stack.size() != 0) {  
                stack.pop();  
            }  
        }  
        String res = "";// 将栈中剩余元素组合成路径  
        for (int i = 0; i < stack.size(); i++) {  
            res = "/" + stack.get(stack.size() - 1 - i) + res;  
        }  
        if (res.equals("")) // 防止/../情况  
            res = "/";  
        return res;  
    }  


以上是关于Leetcode Simplify Path的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 71 Simplify Path

Leetcode 之Simplify Path(36)

Leetcode - Simplify Path

leetcode - Simplify Path

LeetCode 71. Simplify Path

Leetcode 71: Simplify Path