输入:一个字符串 path,它是一个 Unix 风格的绝对路径。
要求:将给定的绝对路径转换为简化的“规范路径”。规范路径需遵循:
-
始终以一个
/开头。 -
两个目录名之间有且只有一个
/。 -
路径不能以
/结尾(除非是/)。 -
.(当前目录) 应被忽略。 -
..(上一级目录) 应移除上一级目录。 -
连续的
//应被视为一个/。
输出:一个字符串,表示简化后的规范路径。
思路1:使用字符栈模拟。遍历路径字符串,以字节为单位进行处理。
复杂度:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
string simplifyPath(string path) {
string s = path + "/";
int len = s.size();
stack<char> tmp;
for (int i = 0; i < len; i++) {
if (s[i] != '/') {
tmp.push(s[i]);
}
else {
if (tmp.empty()) {
tmp.push(s[i]);
}
else if (tmp.top() == '.') {
if (s[i-2] == '/') {
tmp.pop();
}
else if (s[i-2] == '.' && s[i-3] == '/') {
tmp.pop();
tmp.pop();
if (tmp.size() == 1) {
continue;
}
tmp.pop();
while (tmp.top() != '/') {
tmp.pop();
}
}
else {
tmp.push(s[i]);
}
}
else if (tmp.top() == '/') {
//无视此项
}
else {
tmp.push(s[i]);
}
}
}
if (tmp.top() == '/' && tmp.size() > 1) {
tmp.pop();
}
string ans;
while (!tmp.empty()) {
ans += tmp.top();
tmp.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
思路2:先将字符串分割,然后再进行处理,以字符串为单位进行处理。
复杂度:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
string simplifyPath(string path) {
vector<string> dirs; // 用 vector 模拟栈
stringstream ss(path);
string component;
// 按 '/' 分割字符串
while (getline(ss, component, '/')) {
if (component.empty() || component == ".") {
continue;
}
else if (component == "..") {
if (!dirs.empty()) {
dirs.pop_back();
}
}
else {
dirs.push_back(component);
}
}
// 将栈中的有效目录拼接成最终路径
if (dirs.empty()) {
return "/";
}
string ans;
for (const string& dir : dirs) {
ans += "/" + dir;
}
return ans;
}
};
1615

被折叠的 条评论
为什么被折叠?



