搜狐2017笔试题----Unix路径简化

题目描述

简化Unix风格的路径,需要考虑的包括"/../","//","/./"等情况

输入描述

Unix风格的路径

输出描述

简化后的Unix风格路径

示例输入

/a/./b/../../c/

示例输出

/c

思路

用一个栈来存储路径中的目录信息,遍历读入的string字符串,当遇到‘/’时跳过,遇到不为‘/’的字符时累加从而得到当前目录信息,若目录为‘.’,则continue,若目录为‘..’且栈不为空则pop,否则push该目录到栈中。

循环结束后,栈中的目录则为简化后的目录,但排序为逆序,则通过再次循环累加到string变量中(注意加‘/’),输出该变量。

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

using namespace std;

int main(){
	string str;
	cin >> str;
	int len = str.length();
	stack<string> stringStack;
	int i = 0;
	string tmp;
	while (i < len)
	{
		while (i < len && str[i] == '/')
			i++;

		tmp.clear();
		while (i < len && str[i] != '/')
		{
			tmp += str[i];
			i++;
		}
		if (tmp == "..")
		{
			if (!stringStack.empty())
				stringStack.pop();
		}
		else if (tmp == ".")
			continue;
		else if (!tmp.empty())
		{
			stringStack.push(tmp);
		}
	}
	if (stringStack.empty()){
		cout << "/";
		return 0;
	}
	string result = "";
	while (!stringStack.empty())
	{
		result = "/" + stringStack.top() + result;
		stringStack.pop();
	}
	cout << result;

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值