码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Simplify Path

时间:2014-05-26 06:13:24      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:path   algorithm   leetcode   面试题   

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

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

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

bubuko.com,布布扣

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;
}


【leetcode】Simplify Path,布布扣,bubuko.com

【leetcode】Simplify Path

标签:path   algorithm   leetcode   面试题   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/26752451

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!