LeetCode: Simplify Path Solution

Approach

Split the task by slash /

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

1function 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 === 0
18 }
19}
20
21/**
22 * @param {string} path
23 * @return {string}
24 */
25var simplifyPath = function (path) {
26 path = path
27 .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}

Comments

Loading comments...

Tags

leetcode

string

stack

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Reverse Integer

Previous Post

LeetCode: Single Number

Count occurence of each element

HoningJS

Search Posts