71. Simplify Path
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"
.
链接:https://leetcode.com/problems/simplify-path/#/description
5/27/2017
9ms. 86%
注意的问题:
1. LinkedList当作stack的push, pop:操作在链表头。list.push(1), list.push(2)画图表示出来为2->1,所以此时list.get(0)返回的应该是2。不要想当然认为是从尾巴开始加,毕竟对于链表最方便的操作就是在表头。
2. 如果记不住前一点,就用removeLast, addLast来表示好了
3. 26行注意判断是否返回的是root
1 public class Solution { 2 public String simplifyPath(String path) { 3 if (path == null || path.length() == 0 || path.equals("")) { 4 return ""; 5 } 6 LinkedList<String> list = new LinkedList<String>(); 7 String[] parts = path.split("/"); 8 9 for (int i = 0; i < parts.length; i++) { 10 if (parts[i].equals("") || parts[i].equals(".")) continue; 11 else if (parts[i].equals("..")) { 12 if (list.isEmpty()) continue; 13 else { 14 list.removeLast(); 15 } 16 } else { 17 list.addLast(parts[i]); 18 } 19 } 20 StringBuilder sb = new StringBuilder(); 21 int size = list.size(); 22 for (int i = 0; i < size; i++) { 23 sb.append("/"); 24 sb.append(list.get(i)); 25 } 26 return sb.length() == 0? "/": sb.toString(); 27 } 28 }
更多讨论:
https://discuss.leetcode.com/category/79/simplify-path
以上是关于71. Simplify Path的主要内容,如果未能解决你的问题,请参考以下文章