Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save superlayone/b2bd964d0fe8a6b22f9d to your computer and use it in GitHub Desktop.

Select an option

Save superlayone/b2bd964d0fe8a6b22f9d to your computer and use it in GitHub Desktop.
Simplify Path

##UNIX路径简化

今天做了一道比较有意思的题目,处理UNIX路径的字符串操作。

path = "/home/", => "/home"

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

路径中/表示根,.表示当前目录,..表示父级目录

思路

使用栈保存路径

    string simplifyPath(string path) 
    {
    	string result = "";
    	vector<string> pathStack;
    	for(auto i = path.begin(); i != path.end();)
    	{
    		i++;
    		auto j = find(i,path.end(),'/');
    		string dir = string(i,j);
    		if(!dir.empty() && dir != ".")
    		{
    			//parent dir
    			if(dir == "..")
    			{
    				if(!pathStack.empty())
    				{
    					pathStack.pop_back();
    				}
    			}
    			//dir
    			else
    			{
    				pathStack.push_back(dir);
    			}
    		}
    		//update pos
    		i = j;
    	}
    	if(pathStack.empty())
    	{
    		return "/";
    	}
    	else
    	{
    		for(auto dir : pathStack)
    		{
    			result += "/";
    			result += dir;
    		}
    		return result;
    	}
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment