Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

简化路径 #67

Open
louzhedong opened this issue Sep 20, 2018 · 0 comments
Open

简化路径 #67

louzhedong opened this issue Sep 20, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第71题

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

边界情况:

  • 你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回 "/"
  • 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/"
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo"

思路

首先区分几种情况,当两个斜杠之间为空或者为'.' 时,当前目前层级不变。当两个斜杠之间为'..'时,当前目录需要前移一级。使用一个数组保存每一级的文件名,每有一个新的就push一个元素,没前移一级就pop一个元素,最后将所有的元素用斜杠串联起来。

解答

/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function (path) {
  var pathArray = path.split('/');
  var current = [];
  for (var i = 0; i < pathArray.length; i++) {
    if (pathArray[i] != '.' && pathArray[i] != '..' && pathArray[i] != '') {
      current.push(pathArray[i]);
    }
    if (pathArray[i] == '..') {
      if (current.length > 0) {
        current.pop();
      }
    }
  }
  return '/' + current.join('/');
};

console.log(simplifyPath("/home//foo/"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant