Simplify Path

来源:互联网 发布:2016网络神曲排行榜 编辑:程序博客网 时间:2024/04/25 17:13

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

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

click to show corner cases.

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

Subscribe to see which companies asked this question.

解题技巧:

1. 重复连续出现的 '/',只按1个处理,即:跳过重复连续出现的 '/';

2. 如果路径名是 ".",则不处理;

3. 如果路径名是 "..",则需要弹栈。如果栈为空,则不做处理;

4. 如果路径名为其他字符串,入栈。

5. 最终的结果是从栈中逐个取出元素,用'/'分隔并连接起来,不过要注意顺序。

代码:

#include <iostream>#include <stack>using namespace std;string simplifyPath(string path){     int len = path.size();     stack<string> stack1;     for(int i = 0; i < len; i++)     {         //跳过'/'         while(i < len && path[i] == '/')            i++;         //提取两个'/'之间的字符串         string tmp = "";         while(i < len && path[i] != '/')            tmp = tmp + path[i++];         //进行处理         if(tmp == ".")         {             continue;         }         else if(tmp == ".." )         {             if(!stack1.empty())                    stack1.pop();         }         else if(tmp != "")         {             stack1.push(tmp);         }     }     if(stack1.empty()) return "/";     string res = "";     while(!stack1.empty())     {         res = "/" + stack1.top()+res;         stack1.pop();     }     return res;}int main(){    string path;    cin>>path;    cout<<simplifyPath(path);}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 限购房子卖不了怎么办 斑马线礼让行人行人不走怎么办 中国留学生签证在美国被取消怎么办 建行卡网银帐号密码输入错误怎么办 建行卡密码忘了怎么办? 银行卡k宝丢了怎么办 k宝密码锁住了怎么办 农业银行k宝锁了怎么办 银行卡办的网银卡丢了怎么办 事业单位考察档案丢了怎么办 当兵政审家访家里没人在家怎么办 士兵转业结婚材料不全怎么办 体育生训练腿疼怎么办 车底盘刮的严重怎么办 新车底盘被刮了怎么办 车侧面刮凹了怎么办 憋气久了想呕吐怎么办 19岁网贷欠了3万怎么办 大学生欠2w网贷怎么办 当兵去了网贷怎么办 考公安视力不过关怎么办 身份证号和姓名电话泄露了怎么办 黑色裙子被染色了怎么办 戴墨镜鼻子太塌怎么办 戴墨镜鼻子有印怎么办 戴眼镜鼻梁塌了怎么办 站的时间长了腿疼怎么办 小孩腿筋拉伤了怎么办 走多了小腿骨疼怎么办 走多了一个腿疼怎么办 走太多路腿酸痛怎么办 老年人脚肿并痛怎么办 孩子蛙跳肌后大腿痛怎么办 走路久了腿酸怎么办 走路多了膝盖痛怎么办 走路多了小腿痛怎么办 走多了腿疼怎么办 小腿走多了酸痛怎么办 腿肚受凉了酸痛怎么办 晚上腿疼的睡不着觉怎么办 走路走多了腿酸怎么办