# Leetcode 71 简化路径
2024-04-22 本文已影响0人
Aaron_Swartz
leetcode第71题: 简化路径
https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150
// 我的解法
string simplifyPath(string path)
{
stack<string> s;
// ./ ../ //
char dot = '.';
char g = '/';
string dir;
bool flag = false;
string pattern;
string folder;
for (int i = 0;i < path.size(); ++i)
{
if (path[i] == 'd')
cout << "get into" << endl;
if (i == 0 && path[i] == g)
continue;
if (path[i] == dot)
{
flag = true;
pattern += dot;
//continue;
}
if (flag && path[i] == '/')
{
if (pattern == LAST || pattern == CURRENT)
{
if (pattern == LAST)
{
if (!s.empty())
s.pop();
}
// current直接delete
flag = false;
pattern.clear();
}
else {
// 为 ....等其他形式
s.push(folder);
pattern.clear();
folder.clear();
}
continue;
}
if (path[i] == '/')
{
if (!folder.empty())
{
s.push(folder);
folder.clear();
}
continue;
}
folder += path[i];
}
if (pattern == LAST || pattern == CURRENT)
{
if (!s.empty() && pattern == LAST)
{
s.pop();
}
pattern.clear();
}
if (!pattern.empty())
s.push(pattern);
if (!folder.empty())
{
s.push(folder);
}
string res;
while (!s.empty())
{
res = "/" + s.top() + res;
s.pop();
}
return !res.empty() ? res : "/";
}
当你的循环已经非常复杂,逻辑已经很乱时,需要想当肯定是方法出现了问题,需要尽快转变思维,跳出来
// 实际借助字符分割很快就解决了
class Solution {
public:
string simplifyPath(string path) {
auto split = [](const string& s, char delim) -> vector<string> {
vector<string> ans;
string cur;
for (char ch: s) {
if (ch == delim) {
ans.push_back(move(cur));
cur.clear();
}
else {
cur += ch;
}
}
ans.push_back(move(cur));
return ans;
};
vector<string> names = split(path, '/');
vector<string> stack;
for (string& name: names) {
if (name == "..") {
if (!stack.empty()) {
stack.pop_back();
}
}
else if (!name.empty() && name != ".") {
stack.push_back(move(name));
}
}
string ans;
if (stack.empty()) {
ans = "/";
}
else {
for (string& name: stack) {
ans += "/" + move(name);
}
}
return ans;
}
};