Skip to content
On this page

71. Simplify Path

https://leetcode.com/problems/simplify-path/

js
/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
  path = path.substring(1).split('/')
  var result = []
  for (let p of path) {
    if (!p || p === '.') {
      continue
    } else if (p === '..') {
      result.pop()
    } else {
      result.push(p)
    }
  }
  return '/' + result.join('/')
}
py
class Solution(object):

    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        path = path[1:].split('/')
        result = []
        for p in path:
            if not p or p == '.':
                continue
            elif p == '..':
                if len(result):
                    result.pop()
            else:
                result.append(p)
        return '/' + '/'.join(result)