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;
    }
};
相关推荐
csdn_aspnet10 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_6294947313 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
小羊在睡觉18 小时前
力扣239. 滑动窗口最大值
数据结构·后端·算法·leetcode·go
大大杰哥18 小时前
leetcode hot100(4)矩阵
算法·leetcode·矩阵
叶小鸡19 小时前
小鸡玩算法-力扣HOT100-动态规划(上)
算法·leetcode·动态规划
凌波粒19 小时前
LeetCode--513.找树左下角的值(二叉树)
java·算法·leetcode
一只小逸白21 小时前
LeetCode Go 常用函数速查表
linux·leetcode·golang
Tisfy1 天前
LeetCode 3043.最长公共前缀的长度:哈希表(不转string)
算法·leetcode·散列表·题解·哈希表
承渊政道1 天前
【贪心算法】(经典实战应用解析(六):整数替换、俄罗斯套娃信封问题、可被三整除的最⼤和、距离相等的条形码、重构字符串)
c++·算法·leetcode·贪心算法·排序算法·动态规划·哈希算法
人道领域1 天前
【LeetCode刷题日记】654.最大二叉树:递归算法详解
java·算法·leetcode