Skip to content

71. 简化路径

71. 简化路径

代码

javascript
// 71. 简化路径:https://leetcode.cn/problems/simplify-path/description/
// 输入:'/home/user/Documents/../Pictures'
// 输出:'/home/user/Pictures'

export function simplifyPath (path) {
  const pathList = path.split('/').filter(item => !['', '.'].includes(item))
  const stack = []
  pathList.forEach(item => {
    if (item === '..') {
      stack.pop()
    } else {
      stack.push(item)
    }
  })
  return `/${stack.join('/')}`
}
typescript
// 71. 简化路径:https://leetcode.cn/problems/simplify-path/description/
// 输入:'/home/user/Documents/../Pictures'
// 输出:'/home/user/Pictures'

export function simplifyPath (path: string): string {
  const pathList = path.split('/').filter(item => !['', '.'].includes(item))
  const stack: string[] = []
  pathList.forEach(item => {
    if (item === '..') {
      stack.pop()
    } else {
      stack.push(item)
    }
  })
  return `/${stack.join('/')}`
}

测试代码

ts
import { expect, test } from 'vitest'
import { simplifyPath } from './typescript.ts'
import { simplifyPath as simplifyPathJs } from './javascript.js'

test(`simplifyPath`, () => {
  expect(simplifyPath('/home/')).toBe('/home')
  expect(simplifyPath('/home//foo/')).toBe('/home/foo')
  expect(simplifyPath('/home/user/Documents/../Pictures')).toBe('/home/user/Pictures')
  expect(simplifyPath('/../')).toBe('/')
  expect(simplifyPath('/.../a/../b/c/../d/./')).toBe('/.../b/d')
})

test(`simplifyPathJs`, () => {
  expect(simplifyPathJs('/home/')).toBe('/home')
  expect(simplifyPathJs('/home//foo/')).toBe('/home/foo')
  expect(simplifyPathJs('/home/user/Documents/../Pictures')).toBe('/home/user/Pictures')
  expect(simplifyPathJs('/../')).toBe('/')
  expect(simplifyPathJs('/.../a/../b/c/../d/./')).toBe('/.../b/d')
})