Re: [闲聊] 每日LeetCode

楼主: pandix (面包屌)   2023-04-12 15:26:06
71. Simplify Path
给你一个 unix-style 的资料夹路径要你简化他
简化后符合以下规范:
1.路径以'/'开头 2.资料夹间以单个'/'隔开 3.不以'/'结尾 4.不含'.'或'..'
Example 1:
Input: path = "/home/"
Output: "/home"
Example 2:
Input: path = "/../"
Output: "/"
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
思路:
1.先以 '/' split 一次路径得到分开的资料夹名称
出现 '..' 代表回到上一层 -> 也就是删掉自己左边那个资料夹 和昨天的题目很像 用 stack
input path 会有双斜线所以要把空字串判断掉
Python code:
class Solution:
def simplifyPath(self, path: str) -> str:
res = []
for dir in path.split('/'):
if dir == '..':
if res:
res.pop()
elif dir and dir != '.':
res.append(dir)
return '/'+'/'.join(res)
作者: Rushia (みけねこ的鼻屎)   2023-04-12 17:14:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com