码迷,mamicode.com
首页 > 其他好文 > 详细

lc 简化路径

时间:2020-05-18 00:23:56      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:int   span   img   amp   xpl   imp   include   图片   https   

链接:https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1013/

代码:

技术图片
#include <stack>
class Solution {
public:
    string simplifyPath(string path) {
        int len = path.size();
        int i = 0;
        stack<string> s;
        while(i < len) {
            while(i < len && path[i] == /) {
                i++;
            }
            int flag1 = 0;
            int flag2 = 0;
            int flag3 = 0;
            if((i<len&&i+1<len&&i+2<len) && path[i]==. && path[i+1] == . && path[i+2] != /) flag1 = 1;
            if((i<len&&i+1<len) && path[i] == . && path[i+1] != / && path[i+1] != .) flag2 = 1;
            if(i < len && path[i] != .) flag3 = 1;
            if(flag1 || flag2 || flag3) {
                cout << "flag123" << endl;
                // in stack
                string temp = "";
                while(i < len && path[i] != /) {
                    temp += path[i];
                    i++;
                }
                s.push(temp);
                continue;
            }
            int flag4 = 0;
            if((i<len&&i+1<len) && path[i] == . && path[i+1] == .) flag4 = 1;
            if(flag4) {
                cout << "flag4" << endl;
                // .. if valid, back to previous layer
                if(!s.empty()) {
                    s.pop();
                }
                i += 2;
                continue;
            }
            int flag5 = 0;
            if(i < len && path[i] == .) flag5 = 1;
            if(flag5) {
                cout << "flag5" << endl;
                // . stay the same
                i++;
                continue;
            }
        }
        if(s.empty()) return "/";
        stack<string> ans;
        while(!s.empty()) {
            ans.push(s.top());
            s.pop();
        }
        string res = "";
        while(!ans.empty()) {
            res += "/";
            res += ans.top();
            ans.pop();
        }
        return res;
    }
};
View Code

思路:字符串切割,注意"..*" ".*" "../" "./"情况要好好讨论,不能先讨论前缀,再运用栈(主要是".."类似于弹栈操作)输出。

lc 简化路径

标签:int   span   img   amp   xpl   imp   include   图片   https   

原文地址:https://www.cnblogs.com/FriskyPuppy/p/12907849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!