标签:ase append size pop home where etc 一点 null
题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
"/../"
?"/"
.‘/‘
together, such as "/home//foo/"
."/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
标签:ase append size pop home where etc 一点 null
原文地址:http://www.cnblogs.com/panini/p/6914959.html