LeetCode 题解(16): Simplify Path

题目:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:
  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
题解:

1. 将输入字符串以'/'为分隔符分割成子串保存在字符串数组中

2. 遍历1生成的字符串数组,每当碰到非"."和".."的字符串,就将该字符串前加"/",并压入到一个字符串堆栈中(用vector实现,方便最后拼接路径)

    每当碰到"."时,直接continue

    每当碰到".."时,堆栈弹出一个元素

3. 遍历完成后,将堆栈中剩余的字符串按先进先出的顺序(用vector可以两端访问元素)拼接成最后的路径

     若堆栈为空,则返回"/"。


class Solution {
public:
    string simplifyPath(string path) {
        if(!path.length())
            return path;
        vector<string> split;

        for(int i = 0; i < path.length();)
        {
            if(path[i] == '/')
            {
                i++;
                continue;
            }
            else {
                string temp = "";
                while(path[i] != '/' && i < path.length())
                {
                    temp.insert(temp.length(), 1, path[i++]);
                }
                split.push_back(temp);
            }
        }
        
        vector<string> combine;
        for(int i = 0; i < split.size(); i++)
        {
            if(split[i] != "." && split[i] != "..")
            {
                string path1 = "";
                path1.insert(path1.length(), 1, '/');
                path1.insert(path1.length(), split[i]);
                combine.push_back(path1);
            }
            else if(split[i] == ".." && combine.size())
            {
                combine.pop_back();
            }
            else{
                continue;
            }
        }
        
        string final = "";
        if(!combine.size())
        {
            final.insert(final.length(), 1, '/');
        }
        for(int i = 0; i < combine.size(); i++)
        {
            final.insert(final.length(), combine[i]);
        }
        return final;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值