zoukankan      html  css  js  c++  java
  • lc 简化路径

    链接: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

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

  • 相关阅读:
    Web安全
    前端安全之XSS攻击
    SQL盲注
    Vim使用手册
    VC获取cookies的几种方法
    Wireshark基本介绍和学习TCP三次握手
    细说Cookie
    top100tools
    如何更改Jframe里Jpanel的大小
    HTTP&&Fiddler教程
  • 原文地址:https://www.cnblogs.com/FriskyPuppy/p/12907849.html
Copyright © 2011-2022 走看看