王廷瑋|數位醫療|智慧醫療: 71. Simplify Path WFU

2024年7月4日 星期四

71. Simplify Path

71. Simplify Path


給定一個 Unix 風格的文件系統的絕對路徑,它以斜杠 '/' 開頭,將此路徑轉換為其簡化的標準路徑。

在 Unix 風格的文件系統上下文中,單個句點 '.' 表示當前目錄,雙句點 '..' 表示向上一級目錄,多個斜杠如 "//" 被解釋為單個斜杠。在這個問題中,將不受前述規則覆蓋的句點序列(如 "...")視為有效的文件或目錄名稱。

簡化的標準路徑應遵循以下規則:必須以單個斜杠 '/' 開頭。
路徑中的目錄應以單個斜杠 '/' 分隔。
除非是根目錄,否則它不應以斜杠 '/' 結尾。
它應排除用於表示當前或父目錄的單個或雙個句點。

返回新的路徑。

範例 1:

輸入:path = "/home/" 輸出:"/home" 解釋:應該移除尾部的斜杠。


Python


class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
components = path.split('/')
for component in components:
if component == '' or component == '.':
continue
elif component == '..':
if stack:
stack.pop()
else:
stack.append(component)
return '/' + '/'.join(stack)

16.48MB, 39ms


C++


#include <vector>
#include <string>
#include <sstream>

using namespace std;

class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
stringstream ss(path);
string component;

while (getline(ss, component, '/')) {
if (component == "" || component == ".") {
continue;
} else if (component == "..") {
if (!stack.empty()) {
stack.pop_back();
}
} else {
stack.push_back(component);
}
}

string result = "/";
for (size_t i = 0; i < stack.size(); ++i) {
result += stack[i];
if (i != stack.size() - 1) {
result += "/";
}
}

return result;
}
};

9.74MB, 4ms


Javascript

/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
let stack = [];
let components = path.split('/');
for (let component of components) {
if (component === '' || component === '.') {
continue;
} else if (component === '..') {
if (stack.length > 0) {
stack.pop();
}
} else {
stack.push(component);
}
}
return '/' + stack.join('/');
};

51.01MB, 57ms