LeetCode 71. Simplify Path
2016-04-04 18:01
344 查看
Unix-style的path中,"."表示当前目录下的子目录,".."表示返回上一级目录,"..."的话保留(Input:"/..." Expected answer:"/...")。
因此维护一个stack,存放路径中文件夹的名字name,将path打散(split)后,一段段读入,如果是"."则继续读入下一段,如果是".."则将name的顶端pop掉,注意此处要检测name是否为空,因为输入有"/../",如果这两种都不是就压入name栈中。
自己写了个split函数,把path按"/"分开,因为有检测tmp是否为空,所以nodes里的所有string均不为空。注意split中for循环后,如果tmp不为空要压入nodes中(path最后一部分可能为“/abcd")。
最后如果name栈为空,res设为"/",否则将栈内依次加入res。
注意!name.empty()的位置,不能写成if(nodes[i] == ".." && !name.empty()),否则".."会被压入name中。
另外一种split的写法,时间相同,注意这种写法nodes中的内容可能为空,因此读入nodes[i]时要检测是否为空,为空则继续(Input:"///" Expected answer:"/")。
总结一下,个人认为比较特殊的输入和标准输出:
Input Expected answer
"///" "/"
"/..." "/..."
"/../" "/"
因此维护一个stack,存放路径中文件夹的名字name,将path打散(split)后,一段段读入,如果是"."则继续读入下一段,如果是".."则将name的顶端pop掉,注意此处要检测name是否为空,因为输入有"/../",如果这两种都不是就压入name栈中。
自己写了个split函数,把path按"/"分开,因为有检测tmp是否为空,所以nodes里的所有string均不为空。注意split中for循环后,如果tmp不为空要压入nodes中(path最后一部分可能为“/abcd")。
最后如果name栈为空,res设为"/",否则将栈内依次加入res。
注意!name.empty()的位置,不能写成if(nodes[i] == ".." && !name.empty()),否则".."会被压入name中。
class Solution { public: void split(string str, char ch, vector<string>& nodes){ string tmp = ""; for(int i = 0; i < str.length(); ++i){ if(str[i] == '/'){ if(tmp != ""){ nodes.push_back(tmp); } tmp = ""; } else { tmp += str[i]; } } if(tmp != "")//input: path = "/..." expected:"/..." nodes.push_back(tmp); } string simplifyPath(string path) { vector<string> nodes; split(path, '/', nodes); stack<string> name; for(int i = 0; i < nodes.size(); ++i){ if(nodes[i] == ".") continue;//nodes[i] == "" || if(nodes[i] == ".."){//input: path = "/../" if(!name.empty()) name.pop(); } else name.push(nodes[i]); } string res = ""; while(!name.empty()){ res = "/" + name.top() + res; name.pop(); } if(res.empty()) res = "/"; return res; } };
另外一种split的写法,时间相同,注意这种写法nodes中的内容可能为空,因此读入nodes[i]时要检测是否为空,为空则继续(Input:"///" Expected answer:"/")。
class Solution { public: void split(string s, char delim, vector<string>& nodes) { string temp; stringstream ss; //here ss.str(s); //here while(getline(ss, temp, delim)) { nodes.push_back(temp); } } string simplifyPath(string path) { vector<string> nodes; split(path, '/', nodes); stack<string> name; for(int i = 0; i < nodes.size(); ++i){ if(nodes[i] == "" || nodes[i] == ".") continue;// if(nodes[i] == ".."){//path = "/../" if(!name.empty()) name.pop(); } else name.push(nodes[i]); } string res = ""; while(!name.empty()){ res = "/" + name.top() + res; name.pop(); } if(res.empty()) res = "/"; return res; } };
总结一下,个人认为比较特殊的输入和标准输出:
Input Expected answer
"///" "/"
"/..." "/..."
"/../" "/"
相关文章推荐
- Hive分析窗口函数之CUME_DIST和PERCENT_RANK
- 【转载】MFC的程序执行顺序
- C++智能指针
- 时光商店下载网页设计
- CodeForces 651B Beautiful Paintings
- CodeForces 651B Beautiful Paintings
- 程序猿,你为什么须要一台mac?
- PHP--仿微信, 通过登陆者用户名显示好友列表,显示头像和昵称
- CPU处理多任务——中断与轮询方式比较
- LeetCode之2_Add Two Numbers
- log4j 五分钟生成一个文件(代码)
- ImageButton和ImageView的使用
- gtk 开发实践第三篇
- HDU-1711-kmp模板
- iOS设计模式之生成器
- 如何激活webstorm 11
- 内存字节对齐
- java堆内存的划分
- 画图
- CodeForces 651 C Watchmen