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