`

LeetCode 71 - Simplify Path

 
阅读更多

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

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

 

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".
public String simplifyPath(String path) {
    String[] paths = path.split("\\/+");
    Stack<String> stack = new Stack<>();
    for(String p:paths) {
        if(p.isEmpty() || p.equals(".")) continue;
        if(p.equals("..")) {
            if(!stack.isEmpty()) stack.pop();
        } else {
            stack.push(p);
        }
    }
    if(stack.isEmpty()) return "/";
    String s = "";
    while(!stack.isEmpty()) {
        s = "/"+stack.pop()+s;
    }
    return s;
}

  

分享到:
评论

相关推荐

    js-leetcode题解之71-simplify-path.js

    javascript js_leetcode题解之71-simplify-path.js

    c语言-leetcode题解之0071-simplify-path.zip

    c c语言_leetcode题解之0071_simplify_path.zip

    leetcode双人赛-71.-Simplify-Path-Leetcode:71.-Simplify-Path-Leetcode

    leetcode双人赛71.-Simplify-Path-Leetcode 给定一个字符串路径,它是 Unix 样式文件系统中文件或目录的绝对路径(以斜杠“/”开头),将其转换为简化的规范路径。 在 Unix 风格的文件系统中,句点 '.' 指的是当前...

    _leetcode-python.pdf

    - Simplify Path: 给定一个表示文件系统的路径,请实现一个方法,以简化这个路径。 - Edit Distance: 给定两个单词word1和word2,计算将word1转换为word2所使用的最少操作数。 - Set Matrix Zeroes: 给定一个m×n的...

    leetcode中国-leetcode:leetcode刷题

    leetcode中国 我自己的leetcode刷题记录 ###[20150920] Valid Palindrome Implement strStr() String to Integer ...Simplify Path,字符串处理,stack Length of Last Word,字符串处理.细节题 Rever

    71. Simplify Path**

    71. Simplify Path** https://leetcode.com/problems/simplify-path/ 题目描述 Given an absolute path for a file &#40;Unix-style&#41;, simplify it. Or in other words, convert it to the canonical path. In a...

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...

    java-leetcode面试题解Stack之第71题简化路径-题解.zip

    LeetCode第71题的全称是“Simplify Path”,该题目要求我们编写一个程序,将输入的复杂路径字符串简化为最基础的目录序列。例如,输入的路径可能是"/a/./b/../../c/",输出应该是"/c"。这个问题主要考察的是对字符串...

    c++-c++编程基础之leetcode题解第71题简化路径.zip

    在本压缩包中,主题聚焦于C++编程基础与LeetCode算法题目的解法,特别是针对LeetCode第71题“简化路径”(Simplify Path)的探讨。这道题目旨在检验开发者的路径解析能力,涉及到字符串处理和栈的数据结构应用。让...

Global site tag (gtag.js) - Google Analytics