leetcode[70] Simplify Path
2014-11-12 23:36
274 查看
题目的意思是简化一个unix系统的路径。例如:
path =
path =
我尝试用逐个字符判断的方法,一直提交测试,发现要修改甚多的边界。于是就参考了这位大神
思路其实不会那么复杂,C#里面的话直接可以用split就可以分割string,c++中好像要委婉实现,例如 getline(ss,now,'/')
在c++中getline(istream& is, string& str, char delim)
Extracts characters from is and stores them into str until the delimitation character delim is found
是指将is中的直到下一个delim字符间的数据给str,delim不会在str中,如果delim缺省,那么默认‘\n'
因为文件流是往后读,读到文件末尾为止,所以用while来处理,详见代码。
(1)用“/”分割字符串,遍历每个分割部分,存入一个vector<string>中
(2)若当前分割部分为空,证明有连续的"/"或是最后一个“/”,忽略
(3)若当前部分为“.”,忽略
(4)若当前部分为“..”,若vector不为空,去除vector最后一个元素
(5)再将vector中的string用“/”连起来,得到结果
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
我尝试用逐个字符判断的方法,一直提交测试,发现要修改甚多的边界。于是就参考了这位大神
思路其实不会那么复杂,C#里面的话直接可以用split就可以分割string,c++中好像要委婉实现,例如 getline(ss,now,'/')
在c++中getline(istream& is, string& str, char delim)
Extracts characters from is and stores them into str until the delimitation character delim is found
是指将is中的直到下一个delim字符间的数据给str,delim不会在str中,如果delim缺省,那么默认‘\n'
因为文件流是往后读,读到文件末尾为止,所以用while来处理,详见代码。
(1)用“/”分割字符串,遍历每个分割部分,存入一个vector<string>中
(2)若当前分割部分为空,证明有连续的"/"或是最后一个“/”,忽略
(3)若当前部分为“.”,忽略
(4)若当前部分为“..”,若vector不为空,去除vector最后一个元素
(5)再将vector中的string用“/”连起来,得到结果
class Solution { public: string simplifyPath(string path) { string ans,now; vector<string> list; stringstream ss(path); while(getline(ss,now,'/')) { if(now.length()==0 || now==".") continue; if(now=="..") { if(!list.empty()) list.pop_back(); } else { list.push_back(now); } } for(int i=0; i<list.size(); i++) { ans += "/"; ans += list[i]; } if(ans.length()==0) ans = "/"; return ans; } };
相关文章推荐
- leetcode: 71. Simplify Path
- [Leetcode]Simplify Path
- [leetcode 70] Climbing Stairs
- Simplify Path——LeetCode
- LeetCode(45) Simplify Path
- [LeetCode] Simplify Path 解题报告
- [LeetCode] 70.爬楼梯
- LeetCode_71---Simplify Path
- 203. Remove Linked List Elements【E】【70】【leetcode】
- 【LEETCODE】70-Climbing Stairs
- LeetCode-70-Climbing Stairs
- leetCode练习(70)
- [LeetCode] Simplify Path
- LeetCode 071 Simplify Path
- [leetcode 70]Climbing Stairs
- (java)leetcode-70:Climbing Stairs
- LeetCode 71. Simplify Path
- leetcode_middle_70_331. Verify Preorder Serialization of a Binary Tree
- LeetCode-70-Climbing Stairs DP水题Fibonacci
- LeetCode(71) Simplify Path