71. Simplify Path

来源:互联网 发布:stm32f103tbu6编程 编辑:程序博客网 时间:2024/06/05 17:19

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".
Solution 1 Stack
public String simplifyPath(String path) {        String[] strings = path.split("/");Stack<String> stack = new Stack<String>();for (int i = 0; i < strings.length; i++) {String s = strings[i];if (s.equals("..")) {if (stack.isEmpty()) {continue;}stack.pop();} else if (s.equals(".")) {continue;} else if (s.length() == 0) {continue;} else {stack.push(s);}}StringBuilder sb = new StringBuilder();while (!stack.isEmpty()) {sb = new StringBuilder("/").append(stack.pop()).append(sb);}return sb.length() == 0 ? "/" : sb.toString();    }

Solution 2 Dequeue and HashSet
public static String simplifyPath2(String path) {Deque<String> stack = new LinkedList<>();Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));for (String dir : path.split("/")) {if (dir.equals("..") && !stack.isEmpty()) {stack.pop();} else if (!skip.contains(dir)){stack.push(dir);}}StringBuilder sb = new StringBuilder();while(!stack.isEmpty()){sb.append("/").append(stack.pollLast());}return sb.length() == 0 ? "/" : sb.toString();}



0 0