Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

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".

这一题思路很清晰,使用stack来做。只是最后输出的时候要以队列的方式输出。

/../ 返回上一层

/./ 当前层

 1 public class Solution {

 2     public String simplifyPath(String path) {

 3         // Start typing your Java solution below

 4         // DO NOT write main() function

 5         if(path == null) return null;

 6         String[] element = path.split("/");

 7         Stack<String> st = new Stack<String>();

 8         for(int i = 0; i < element.length; i ++){

 9             if(element[i].length() != 0){

10                 if(element[i].equals("..")){

11                     if(st.isEmpty() != true)

12                         st.pop();

13                 }else if(element[i].equals(".")){

14                 }else{

15                     st.push(element[i]);

16                 }

17             }

18         }

19         StringBuffer sb = new StringBuffer();

20         if(st.isEmpty() == true){

21             sb.append("/");

22         }else{

23             for(int i = 0; i < st.size(); i ++){

24                 sb.append("/");

25                 sb.append(st.elementAt(i));

26             }   

27         }

28         return sb.toString();

29     }

30 }

 第三遍:

 1 public class Solution {

 2     public String simplifyPath(String path) {

 3         String[] parts = path.split("/");

 4         LinkedList<String> ll = new LinkedList<String> ();

 5         for(int i = 0; i < parts.length; i ++){

 6             System.out.println(parts[i]);

 7             if(parts[i].equals("") || parts[i].equals(".") || (parts[i].equals("..") && ll.size() == 0)) continue;

 8             else if(parts[i].equals("..") && ll.size() != 0) ll.removeLast();

 9             else ll.add(parts[i]);

10         }

11         StringBuffer sb = new StringBuffer();

12         while(ll.size() != 0){

13             sb.append("/");

14             sb.append(ll.remove());

15         }

16         if(sb.length() == 0) sb.append("/");

17         return sb.toString();

18     }

19 }

 

你可能感兴趣的:(Path)