加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

【一天一道LeetCode】#71. Simplify Path

发布时间:2020-12-13 21:06:53 所属栏目:PHP教程 来源:网络整理
导读:1天1道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (1)题目 Given an absolute path for a file (Unix-style),simplify it. For example, path = “/home/”,

1天1道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(1)题目

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”.

(2)解题

题目大意:给定1个绝对路径,简化路径
注意1下几点:

1、“..”表示跳到上1层目录

2、“.”表示当前目录

3、“////”多个/当1个处理

在这里,我们可以利用stack来处理,“..”则把栈顶元素弹出,“.”则不作处理,其他的表示目录的名字就直接压栈。

具体思路可以看代码:

class Solution { public: string simplifyPath(string path) { stack<string> pathStack;//寄存目录 path+="/";//避免处理边界,即/a这类情况 string temp = "";//用作临时string for(int i = 0 ; i< path.length() ;) { if(path[i] == '/') { if(temp=="..") {//返回上1层目录 if(!pathStack.empty()) pathStack.pop();//如果非空则弹出,为空就不做处理 } else if(temp=="."|| temp =="") {}//不做处理,当前目录 else pathStack.push(temp);//正常的目录 while(i<path.length()&&path[i]=='/') i++;//跳过连续的‘/’ temp = "";//temp初始化 } else { temp+=path[i++]; } } string ret; if(pathStack.empty()) ret = "/";//为空时直接输出 else { while(!pathStack.empty())//非空则按格式输出 { string eachPath = pathStack.top(); pathStack.pop(); ret = "/"+eachPath + ret; } } return ret; } };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读