Re: [閒聊] 每日LeetCode已回收
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)
--
蛤?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.200.99 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1681284371.A.2ED.html
※ 編輯: pandix (111.251.200.99 臺灣), 04/12/2023 15:36:11
推
04/12 17:14,
2年前
, 1F
04/12 17:14, 1F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 292 之 719 篇):