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;
    }
};
相关推荐
-优势在我1 小时前
LeetCode之两数之和
算法·leetcode
WaitWaitWait011 小时前
LeetCode每日一题4.17
算法·leetcode
冠位观测者2 小时前
【Leetcode 每日一题】2176. 统计数组中相等且可以被整除的数对
数据结构·算法·leetcode
阳洞洞3 小时前
leetcode 213. House Robber II
算法·leetcode·动态规划
梭七y3 小时前
【力扣hot100题】(099)寻找重复数
算法·leetcode·职场和发展
一叶祇秋6 小时前
Leetcode - 周赛445
算法·leetcode·职场和发展
愚润求学7 小时前
【专题刷题】双指针(三):两数之和,三数之和,四数之和
c++·笔记·leetcode·刷题
get lend gua8 小时前
游戏数据分析,力扣(游戏玩法分析 I~V)mysql+pandas
python·mysql·leetcode·游戏·数据分析
心软且酷丶8 小时前
leetcode:2899. 上一个遍历的整数(python3解法)
python·算法·leetcode
暖阳华笺10 小时前
Leetcode刷题 由浅入深之哈希表——242. 有效的字母异位词
数据结构·c++·算法·leetcode·哈希表