去哪网的笔试题,因为面试的时候也问了,所以记忆清晰,当时好像是没有使用容器,不断地删除字符串处理。这次刚开始想到用栈,后来改的容器,因为要遍历。
// LeetCode_SimplifyPath.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
string simplifyPath(string path) {
vector<string> vec;
int startpos=0,endpos=0;
int i=0;
string ret="";
string temp;
while(i<path.length())
{
startpos = endpos;
i++;
while(i<path.length()&&path[i]!='/')
i++;
endpos = i;
if(endpos-startpos<=1)
continue;
temp = path.substr(startpos+1,endpos - startpos - 1);
if (temp==".")
continue;
if (temp=="..")
{
if(!vec.empty())
vec.pop_back();
}
else
vec.push_back(temp);
}
if (!vec.empty())
{
for (int i=0;i<vec.size();i++)
{
ret += "/";
ret += vec[i];
}
}
else
ret += "/";
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
string path = "/home/..";
cout<<simplifyPath(path)<<endl;
string path2 = "/a/.//b/../../c/";
cout<<simplifyPath(path2)<<endl;
string path3 = "/..";
cout<<simplifyPath(path3)<<endl;
system("pause");
return 0;
}