Leetcode 71 Simply Path

题意:给定一个字符串我要得到简化后的路径。 '...'代表上个路径,'.'代表当前路径

Input: path = "/home/user/Documents/.../Pictures"

Output: "/home/user/Pictures"

https://leetcode.com/problems/simplify-path/description/

解析:首先这道题肯定是从头到尾遍历来做,难点在于我应该用什么判断语句。

如果结尾能够+一个'/'判断会少很多。用一个cur变量来保存当前可以进入栈的元素,用一个栈来存放当前所有的路径,最后重组即可。

cpp 复制代码
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> st;
        string cur;
        string ret;
        if(path.back() != '/') {
            path += '/';
        }
        for(int i = 0; i < path.size(); i++) {
            if(path[i] != '/') {
               cur += path[i];
               continue;
            } else {
                if (cur == "..") {
                    if(st.size()) {
                    st.pop_back();
                    }
                } else if (cur != "." && cur.size()) {
                    st.push_back(cur);
                }
                cur.clear();
            }

        }
            if(!st.size()) return "/";
            for(auto&p : st) {
                ret += '/';
                ret += p;
            }
            return ret;
    }
};

Leetcode 71(错误答案)

这种情形没有考虑到/...hidden/的情形

cpp 复制代码
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> st;
        string ret;
        for(int i = 0; i < path.size(); i++) {
            if(isalpha(path[i])) {
                int j = i;
                while(isalpha(path[j])) j++;
                string p = path.substr(i, j-i);
                st.push_back(p);
                i = j - 1;
            }
            if(path[i] == '.')  {
                int j = i;
                while((path[j] == '.')) j++;
                // one dot
                if(j-i == 1)
                    continue;
                if(j-i == 2) {
                    if(st.size()) {
                        st.pop_back();
                    }
                }
                if(j-i > 2) {
                    string p = path.substr(i, j-i);
                    st.push_back(p);
                }
                i = j - 1;
            }
            if(path[i] == '/') continue;
        }
            if (!st.size()) {
                return "/";
            }
            for(auto&p : st) {
                ret += '/';
                ret += p;
            }
            return ret;
    }
};
相关推荐
yaoh.wang3 分钟前
力扣(LeetCode) 9: 回文数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
小年糕是糕手5 分钟前
【C/C++刷题集】类和对象算法题(一)
数据结构·c++·程序人生·考研·算法·leetcode·改行学it
前端小白在前进1 小时前
力扣刷题:删除排序链表的重复元素Ⅱ
算法·leetcode·链表
ywwwwwwv1 小时前
力扣300
算法·leetcode·职场和发展
努力学算法的蒟蒻1 小时前
day34(12.15)——leetcode面试经典150
算法·leetcode·面试
Chen--Xing1 小时前
LeetCode 11.盛最多水的容器
c++·python·算法·leetcode·rust·双指针
User_芊芊君子2 小时前
【LeetCode经典题解】:从前序和中序遍历构建二叉树详解
算法·leetcode·职场和发展
Elias不吃糖4 小时前
LeetCode 71:简化 Unix 路径(Simplify Path)——栈 / vector
算法·leetcode·
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2025.12.15 题目:2110.股票平滑下跌阶段的数目
笔记·算法·leetcode
lightqjx19 小时前
【算法】双指针
c++·算法·leetcode·双指针