leetcode-71 simplify path

来源:互联网 发布:淘宝客服话术模板 编辑:程序博客网 时间:2024/06/05 15:39

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

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"


路径打印问题,将自己碰到的特殊情况记录如下

1.两个"//"打印为一个"/"

2.出现两个点"/../"需要将上一路径弹出

3.其余情况"/./"忽略不计入最终的结果中

4."."与字符串连接时需要打印 /..hidden---->/..hidden

思路:用栈记录 //之间的字符,

参考了博主 http://blog.csdn.net/makuiyu/article/details/44497901 在此感谢

附上AC代码

class Solution {public:string simplifyPath(string path){stack<string> temp;for (int i = 0; i < path.size();){//找到/之后的字符串while (i < path.size() && path[i] == '/')i++;//找到两个//之间的字符串string ss = "";while (i < path.size() && path[i] != '/'){ss = ss + path[i];i++;}if (ss == "..")    //检查到ss是两个点{if (!temp.empty()){temp.pop();i++;}}else if (ss != "."&&ss != ".."&&ss!=""){temp.push(ss);}}if (temp.empty())return "/";string s="";while (!temp.empty()){s = "/" + temp.top() + s;temp.pop();}return s;}};


0 0
原创粉丝点击