leetcode - 71.Simplify Path

Simplify Path

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

For example,

path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

Solution:

  public String simplifyPath(String path) {
    LinkedList list = new LinkedList<>();
    Set skip = new HashSet<>(Arrays.asList("..", ".", ""));
    for (String dir : path.split("/")) {
      if (dir.equals("..") && !list.isEmpty()) {
        list.removeLast();
      } else if (!skip.contains(dir)) {
        list.add(dir);
      }
    }
    String result = "";
    for (String dir : list) {
      result += "/" + dir;
    }
    return result.isEmpty() ? "/" : result;
  }

你可能感兴趣的:(leetcode题集,leetcode)