Simplify Path

描述

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

For example,

  • path = "/home/", => "/home"
  • path = "/a/./b/../../c/", => "/c"
    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".

分析

很有实际价值的题目。

代码

  1. import java.util.*;
  2. // Simplify Path
  3. // 时间复杂度O(n),空间复杂度O(n)
  4. class Solution {
  5. public String simplifyPath(String path) {
  6. Stack<String> dirs = new Stack<>();
  7. for (int i = 0; i < path.length();) {
  8. ++i;
  9. int j = path.indexOf('/', i);
  10. if (j < 0) j = path.length();
  11. final String dir = path.substring(i, j);
  12. // 当有连续 '///'时,dir 为空
  13. if (!dir.isEmpty() && !dir.equals(".")) {
  14. if (dir.equals("..")) {
  15. if (!dirs.isEmpty())
  16. dirs.pop();
  17. } else {
  18. dirs.push(dir);
  19. }
  20. }
  21. i = j;
  22. }
  23. StringBuilder result = new StringBuilder();
  24. if (dirs.isEmpty()) {
  25. result.append('/');
  26. } else {
  27. for (final String dir : dirs) {
  28. result.append('/').append(dir);
  29. }
  30. }
  31. return result.toString();
  32. }
  33. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/simplify-path.html