题目描述

Leetcode 71. 简化路径 C++

思路

对于这道题目,我们需要知道每一级路径是什么样的(即两个'/'符号之间的内容)。

  1. 如果是'.',表示当前目录,这一级目录实际上什么用处也没有,需要排除。
  2. 如果是'..'表示上一级目录,那么就需要向上返回一级。
  3. 如果两个'/'连在一起,也是多余的,需要去掉。
  4. 另外就是将路径最后面的'/'去掉。

具体做法:
通过双指针(快慢指针)来做。两个位置变量i,j,通过一个while循环来实现,让i指向前一个'/'j指向后一个'/',这样就可以得到一级路径的内容。

因为涉及到要向上返回以及目录,所以可以使用一个堆栈来存储数据,如果需要返回,那么就pop()掉前一个内容就好。

最后将堆栈里面的目录取出,组合就可以得到结果。

解答

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> temp;
        int i=0,j=0;
        while(i<path.size()-1)
        {
            j=i+1;
            while(path[j] != '/') ++j;
            if(i+1 == j)  //说明是//连在一起的情况
            {
                i=j;
                continue;
            }
            string s=path.substr(i,j-i);//截取从i到j(不包含j)的字符串
            if("/." == s)
            {
                i=j;
                continue;
            }
            if("/.." == s && !temp.empty())  temp.pop();
            else if("/.." == s && temp.empty()) ;
            else 
                temp.push(s);
            i=j;
        }
        if(temp.empty()) return "/";
        else
        {
            string res;
            while(!temp.empty())
            {
                res=temp.top()+res;
                temp.pop();
            }
            return res;
        }
    }
};

相关文章:

  • 2021-07-13
  • 2021-07-11
  • 2022-01-12
  • 2021-05-08
  • 2022-12-23
  • 2022-12-23
  • 2021-08-24
  • 2022-03-01
猜你喜欢
  • 2021-05-31
  • 2021-08-16
  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2021-09-04
相关资源
相似解决方案