ES6 solution


  • 0
    Y
    function simplifyPath(path) {
      const pathComponents = path.split('/').filter(pathComponent => pathComponent.length)
      let numUps = 0
      const simplePath = []
      while (pathComponents.length) {
        const pathComponent = pathComponents.pop()
        if (pathComponent === '..') {
          numUps += 1
        } else if (pathComponent === '.') {
          continue
        } else if (numUps) {
          numUps -= 1
        } else {
          simplePath.unshift(pathComponent)
        }
      }
      return `/${simplePath.join('/')}`
    }
    
    console.log(simplifyPath('/home/'))
    console.log(simplifyPath('/a/./b/../../c/'))
    console.log(simplifyPath('/..'))
    console.log(simplifyPath('/...'))
    console.log(simplifyPath('/abc/...'))
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.