Simplify Path CPP

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”

Corner Cases:
• Did you consider the case where path = “/../”?
In this case, you should return “/”.
• Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.

To solve this problem, you should be having a basic idea of unix file navigation.
Below is the basic tutorial:

/ Represents Root Directory.
.. Represents to go up 1 directory from the present directory.
. Represents current directory
/a Represents to move to directory “a”.

Let us analyze with some examples:

/a will go to directory “a”
/a/b will go to directory “b”
/a/.. will go to 1 directory up from present directory. Now the present directory is “a”. Thus it will go to “/”

/a/../b This can be analyzed as below:

/a Go to directory “a”.
/a/.. Go to directory “/”
/a/../b Go to directory b

Hence the result is “b”.

By taking the above inputs, we shall solve “/a/./b/../../c/”

/a Go to directory “a”.
/a/. Go to directory “a” as “.” represents same directory
/a/./b Go to directory “b”.
/a/./b/.. Go to directory “a”. Go 1 level up.
/a/./b/../.. Go to directory “/”. Go 2 level up.
/a/./b/../../c Go to directory “c”.

Thus the result.

We can solve this problem with the help of stacks. This problem is especially designed to check your stacks knowledge.

So while using stacks, we follow below cases:

Case 1: if there are repeated ‘/’, ignore repeated ‘/’.
Case 2: if the string is /./, ignore it.
Case 3: if the string’..’, and stack is not empty, pop out stack one time.
default case: Push the stack.

If return string is empty, return “/”.

Solution in C++

/*
* File     : simplify_path.cpp
*/

#include<iostream>
#include<stack>
#include<string>

using namespace std;


string simplify_path(string path)
{
	stack<string> stack_input;
	string temp_string = "";
	string final_result = "";

	for (int i = 0; i <= path.size(); ++i)
	{
		if (path.size() == i || '/' == path[i])
		{
			//Input the 
			if (!temp_string.empty() && "." != temp_string && ".." != temp_string)
			{
				stack_input.push(temp_string);
			}
			else if (".." == temp_string && !stack_input.empty())
			{
				stack_input.pop();
			}

			temp_string.clear();
			continue;
		}


		temp_string.push_back(path[i]);
	}


	if (stack_input.empty())
		return "/";

	while (!stack_input.empty())
	{
		final_result = "/" + stack_input.top() + final_result;
		stack_input.pop();
	}
	return final_result;
}

int main()
{
	string input_string = "/a/./b/../../c/";
	cout<<"The result string is = "<<simplify_path(input_string)<<endl;

}

Output:

The result string is = /c

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *