ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

给定文件的绝对路径(Linux风格),将其简化为CPP

前开发者教程 八月25,2018
Example,
path = "/home/", => "/home"
path = "/x/./y/../../z/", => "/z"

角落案例:

  • 您是否考虑过这种情况 路径 = “/../”?
    在这种情况下,您应该返回“/”.

另一个极端情况是路径可能包含多个斜线‘/’ together, such as “/home//foo/”.
在这种情况下,您应该忽略多余的斜杠并返回“/home/foo”.

 

要解决此问题,您应该对linux文件导航有一个基本的了解。

以下是基本教程:

 

/代表根目录。

..表示从当前目录上移1个目录。

。代表当前目录

/ a表示移动到目录“ a”。

让我们用一些示例进行分析:

/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.

我们可以借助堆栈来解决此问题。此问题是专门为检查堆栈知识而设计的。

因此,在使用堆栈时,我们遵循以下情况:

情况1: 如果有重复‘/’, ignore repeated ‘/’.

情况2: 如果字符串 is  /./, ignore it.

情况3: 如果字符串’..’,并且堆栈不为空,请弹出堆栈一次。

默认情况: 推入堆栈。

如果返回字符串为空,则返回“/”.

C ++解决方案

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

using namespace std;


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

	for (int i = 0; i <= 路径.size(); ++i)
	{
		if (path.size() == i || '/' == 路径[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;



}

输出量:

The result string is = /c

 

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的
<s class="fhH9Qdp"></s>
<aside class="rybw6Ow"><samp class="Jqz2Gfa"><bdi id="K6GjF4o"><basefont id="XCKOURa" class="XhOsExW"></basefont></bdi></samp></aside>






    • <keygen id="bhYWohv"><textarea id="gJeMbZo"><option id="fPDW7uZ" class="fiVfBlF"><tt class="xFBvMRd"></tt></option></textarea></keygen>