71. Simplify Path

Posted

tags:

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

https://leetcode.com/problems/simplify-path/#/description

难度:85,虽然不难,但是里面关于LinkedList实现的栈的各种技巧的使用,还是有比较高要求的。

先用了String[] split (String  regex)这个函数。先把输入字符串以‘/‘为分隔符分来,如果遇到‘.‘或者空输入什么都不做。如果遇到‘..‘就弹栈。其他情况则将对应元素入栈。这样,栈里面存的就是最后简化的路径,我们只需把栈里面的元素按从末尾到栈顶的顺序取出来,之间添加“/”就可以了。

这里要取栈底元素,用的方法是:stack.removeLast();

还有就是写的时候,忽视了String是一个object, ‘==’表示内存地址都一样的情况,equals才是仅仅值相同的情况

split函数的用法:The string "boo:and:foo", for example, split(":")的结果是 {“boo”, "and", "foo"}; 需要注意的是:Trailing empty strings are not included in the resulting array.比如,split("o")的结果是{“b”, "", ":and:f"}

注意最后是如何顺序写出Stack里的元素

public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>();
    Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));  //new HashSet<>(Arrays.asList("..", ".", ""))---
                                      生成list放到hashset中,为了以后跳过 for (String dir : path.split("/")) { if (dir.equals("..") && !stack.isEmpty()) stack.pop(); else if (!skip.contains(dir)) stack.push(dir); //stack只push非符号项的方法 } String res = ""; for (String dir : stack) res = "/" + dir + res; // .是如何生成/home/foo的, 为何想到用栈 return res.isEmpty() ? "/" : res; // 判断是否为空的情况 }

  

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

71. Simplify Path

leetcode 71 Simplify Path

71. Simplify Path

71. Simplify Path

71. Simplify Path

71. Simplify Path