zoukankan      html  css  js  c++  java
  • 71.Simplify Path

    给定一个字符串,表示一串文件路径,其中 '.','/' 可以跳过,'..' 表示返回上一层路径,输出最终的路径。

    Input: "/a/./b/../../c/"
    Output: "/c"

    Input: "/home//foo/"
    Output: "/home/foo"
    Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.


    思路:
    利用栈来做,因为对于“..” 返回到上一层路径,就相当于栈的先进先出。对于“.”,"/" 跳过。


    注意点:"…" ,OJ判断其为有效的路径。如:"/…",其结果为:"/…"。所以,不能只判断当前节点和前一个节点,需要将非"/"的都用字符串记录下来,碰到下一个"/"的时候再判断其是跳过、出栈、入栈的操作。当跳出for循环后,最后也要判断 字符串中是否还有剩余的值。

    class Solution {
    public:
        string simplifyPath(string path) {
            stack<string> s;
            string res = "", tmp = "";
            int n = path.size();
            for (int i = 0; i < n; i++) {
                if (path[i] == '/') {
                    if (tmp.size() == 0) continue;
                    if (tmp == "..") { //如果是“..”,判断栈中是否为空栈
                        if(s.size()>0) s.pop();
                    }
                    else if(tmp != ".") s.push(tmp);//入栈
                    tmp = "";
                }
                else tmp += path[i];
            }
            if (tmp.size() > 0) {//判断字符串中是否还有值
                if (tmp == "..") {
                    if (s.size() > 0) s.pop();
                }
                else if (tmp != ".") s.push(tmp);
            }
            while (s.size() > 0) {//出栈,转化为结果路径
                res = '/' + s.top() + res;
                s.pop();
            }
            if (res.size() == 0) res += '/';//结果为空时,要返回“/”
            return res;
        }
    };
  • 相关阅读:
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业02
    Django连接MySql数据库
    asyncio异步编程
    Django-rest framework框架
    Git版本管理工具详细教程
    MySQL的sql_mode模式说明及设置
  • 原文地址:https://www.cnblogs.com/luo-c/p/13021041.html
Copyright © 2011-2022 走看看