原题链接在这里: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"
题解:
首先用string.split 把原有path 按照"/"分开 存入 String 数组strArr中.
"."代表当前层. /a/b/. 还是在b folder中.
从前往后扫strArr. 遇到"." 和 " "直接跳过,遇到正常字符就压入栈中,遇到".."时若stack不是空就pop()一次。
得到最后的stack后一个一个出栈加入到StringBuilder中即可。
Note: 注意corner case 如"///", 此时应该返回"/", 但若是用split拆分是返回一个空的strArr, 所以当stack是空的时候,特殊返回"/".
Time Complexity: O(path.length()). Space: O(path.length()).
AC Java:
1 class Solution { 2 public String simplifyPath(String path) { 3 if(path == null || path.length() == 0){ 4 return path; 5 } 6 7 //split string into array 8 //when encoutering "." or " ", continue 9 //when encoutering "..", if stack is not empty, pop stack and return to upper level 10 //when encoutering else, push into stack. 11 String [] parts = path.trim().split("/"); 12 Stack<String> stk = new Stack<>(); 13 for(String part : parts){ 14 if(part.equals(".")){ 15 continue; 16 } 17 18 if(part.equals("..")){ 19 // Either way, when encountering "..", it needs to skip. 20 // Thus it can't combine below if with outter one 21 if(!stk.isEmpty()){ 22 stk.pop(); 23 } 24 25 continue; 26 } 27 28 if(part.length() > 0){ 29 stk.push(part); 30 } 31 } 32 33 StringBuilder sb = new StringBuilder(); 34 while(!stk.isEmpty()){ 35 sb.insert(0, "/"+stk.pop()); 36 } 37 38 // Corner case like "///", it should return "/". 39 if(sb.length() == 0){ 40 sb.insert(0, "/"); 41 } 42 43 return sb.toString(); 44 } 45 }