LeetCode Simplify Path

原题链接在这里: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中。

从前往后扫strArr,遇到"." 和 " "直接跳过,遇到正常字符就压入栈中,遇到".."时若stack不是空就pop()一次。

得到最后的stack后一个一个出栈加入到StringBuilder中即可。

Note:  注意corner case 如"///", 此时应该返回"/", 但若是用split拆分是返回一个空的strArr, 所以当stack是空的时候,特殊返回"/".

Time Complexity: O(path.length()). Space: O(path.length()).

AC Java:

 1 public 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         
12         String [] strArr = path.split("/");
13         Stack<String> stk = new Stack<String>();
14         for(int i = 0; i<strArr.length; i++){
15             if(strArr[i].equals(".") || strArr[i].length() == 0){
16                 continue;
17             }
18             
19             if(strArr[i].equals("..")){
20                 if(!stk.isEmpty()){ //Here we can't combine this if with outter if, since that would affect else statement
21                     stk.pop();
22                 }
23             }else{
24                 stk.push(strArr[i]);
25             }
26         }
27         
28         // Corner case like "///", it should return "/".
29         if(stk.isEmpty()){
30             return "/";
31         }
32         
33         StringBuilder sb = new StringBuilder();
34         while(!stk.isEmpty()){
35             sb.insert(0, "/"+stk.pop());
36         }
37         return sb.toString();
38     }
39 }

 

你可能感兴趣的:(LeetCode Simplify Path)