lintcode-medium-Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
Example
"/home/", => "/home"
"/a/./b/../../c/", => "/c"
Challenge
-
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; } }

浙公网安备 33010602011771号