您的位置:首页 > 其它

leetcode[70] Simplify Path

2014-11-12 23:36 274 查看
题目的意思是简化一个unix系统的路径。例如:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: