标签:
Given an absolute path for a file (Unix-style), simplify it.
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
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"
.
public class Solution { /** * @param path the original path * @return the simplified path */ public String simplifyPath(String path) { // Write your code here if(path == null || path.length() == 0) return path; Stack<String> stack = new Stack<String>(); int i = 0; int j = 1; int len = path.length(); while(j < len){ while(j < len && path.charAt(j) != ‘/‘) j++; String temp = path.substring(i, j); if(temp.equals("/.") || temp.equals("/")){ i = j; j++; } else if(temp.equals("/..")){ if(!stack.isEmpty()) stack.pop(); i = j; j++; } else{ stack.push(temp); i = j; j++; } } if(stack.isEmpty()) return "/"; String res = ""; while(!stack.isEmpty()){ res = stack.pop() + res; } return res; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5357665.html