LeetCode: Simplify Path Solution

Approach

/

Sanitize

• remove
.
because it is the current folter
• remove blank because it is redundant

Use stack, if part is

..
the pop the part, else push the part

Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function Stack() {2  const stack = []3
4  this.push = function (el) {5    stack.push(el)6  }7
8  this.pop = function () {9    return stack.pop()10  }11
12  this.peek = function () {13    return stack[stack.length - 1]14  }15
16  this.isEmpty = function () {17    return stack.length === 018  }19}20
21/**22 * @param {string} path23 * @return {string}24 */25var simplifyPath = function (path) {26  path = path27    .split("/")28    .filter(Boolean)29    .filter(part => part !== ".")30
31  const stack = new Stack()32  for (const part of path) {33    if (part === "..") {34      stack.pop()35    } else {36      stack.push(part)37    }38  }39  const res = []40  while (!stack.isEmpty()) {41    res.push(stack.pop())42  }43  res.reverse()44  return "/" + res.join("/")45}```

leetcode

string

stack

Next Post

LeetCode: Reverse Integer

Feb 5, 2021

Previous Post

LeetCode: Single Number

Feb 4, 2021

Count occurence of each element

Search Posts