71. Simplify Path

Problem:

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

For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"

Corner Cases:

Solution:

Use stack to handle /../.

ONE

RegExp matching.

/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
  return '/' + (path.match(/[^\/]+/g) || [])
    .reduce((stack, p) => {
      if (p === '..') {
        stack.pop()
      } else if (p !== '.') {
        stack.push(p)
      }
      return stack
    }, [])
    .join('/')
};

TWO

Direct search.

/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
  const len = path.length
  const stack = []
  let e = 0
  while (e < len) {
    while (e < len && path[e] === '/') {
      e++
    }
    const s = e
    while (e < len && path[e] !== '/') {
      e++
    }
    if (s < e) {
      const p = path.slice(s, e)
      if (p === '..') {
        stack.pop()
      } else if (p !== '.') {
        stack.push(p)
      }
    }
  }
  return '/' + stack.join('/')
};

Template generated via Leetmark.