首页 > 代码库 > 【leetcode】Simplify Path

【leetcode】Simplify Path

题目:将给定的路径名简化,返回最简形式。

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

虽然咋看起来比较杂乱,但还是比较整齐的,每个部分由‘/‘进行分割,就像文本处理中,由空格或tab分割的单词一样,对得到的不同的分割此进行不同的处理。得到的可能的分割词包括:


string simplifyPath(string path) {

	if(path.size() <= 1 || path[0] != '/')
		return path;

	vector<string> simPath;
	int path_len = path.size();

	int i = 0;
	while (i < path_len)
	{
		int next_slash = path.find('/', i + 1);
		//find the next slash
		string strBetweenSlash;
		if(next_slash != path.npos)
		{
			strBetweenSlash = path.substr(i, next_slash - i);
		}
		//not find
		else{
			strBetweenSlash = path.substr(i, path_len - i);
			next_slash = path_len;
		}
		//back to parent dir
		if(strBetweenSlash.compare("/..") == 0)
		{
			if(!simPath.empty())
				simPath.pop_back();
			else
			{
				i = next_slash;
				continue;
			}
		}
		//skip
		else if(strBetweenSlash.compare("/") == 0)
		{
			i = next_slash;
			continue;
		}
		//back to current dir,skip
		else if(strBetweenSlash.compare("/.") != 0)
		{
			simPath.push_back(strBetweenSlash);
		}
		i = next_slash;
	}
	if(simPath.empty())
		return "/";
	string re;
	//get the whole dir
	vector<string>::const_iterator cite = simPath.begin();
	while (cite != simPath.end())
	{
		re += *cite;
		++cite;
	}
	return re;
}