LeetCode Simplify Path

本文介绍了一种简化文件路径的算法实现,通过使用C++中的vector容器来处理包含'..'和'.'等特殊符号的路径字符串,最终返回规范化的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

去哪网的笔试题,因为面试的时候也问了,所以记忆清晰,当时好像是没有使用容器,不断地删除字符串处理。这次刚开始想到用栈,后来改的容器,因为要遍历。

// LeetCode_SimplifyPath.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;

string simplifyPath(string path) {
	vector<string> vec;
	int startpos=0,endpos=0;
	int i=0;
	string ret="";
	string temp;
	while(i<path.length())
	{
		startpos = endpos;
		i++;
		while(i<path.length()&&path[i]!='/')
			i++;
		endpos = i;
		if(endpos-startpos<=1)
			continue;
		temp = path.substr(startpos+1,endpos - startpos - 1);
		if (temp==".")
			continue;
		if (temp=="..")
		{
			if(!vec.empty())
				vec.pop_back();
		}
		else
			vec.push_back(temp);
	}
	
	if (!vec.empty())
	{
		for (int i=0;i<vec.size();i++)
		{
			ret += "/";
			ret += vec[i];
		}
	}
	else
		ret += "/";
	return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
	string path = "/home/..";
	cout<<simplifyPath(path)<<endl;
	string path2 = "/a/.//b/../../c/";
	cout<<simplifyPath(path2)<<endl;
	string path3 = "/..";
	cout<<simplifyPath(path3)<<endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值