71.简化路径

71.简化路径

class Solution {
public:
    string simplifyPath(string path);
};

string Solution::simplifyPath(string path)
{
	//去掉所有多余的"/"
	regex regex3("\\/{2,}");
	path = regex_replace(path, regex3, "/");
	regex regex2("\\/{1}\\.{0,2}");
	if (regex_match(path, regex2))
		return "/";
	regex regex1("\\/{1}[\\.a-z]*");
	if (regex_match(path, regex1)) {
		return path;
	}
	path += '/';
	//替换单个point
	smatch sm;
	regex reg_single_point("\\/{1}\\.{1}\\/{1}");
	while (regex_search(path, reg_single_point))
	{
		path = regex_replace(path, reg_single_point, "/");
	}

	//处理两个point
	regex reg_double_point("[\\/]{1}[\\.]{2}[\\/]{1}");
	while (regex_search(path, sm, reg_double_point))
	{
		string str_head = sm.prefix();
		string str_tail = sm.suffix();
		for (int i = str_head.length() - 1; i >= 0; --i) {
			if (str_head[i] == '/')
			{
				str_head.erase(i);
				break;
			}
		}
		path = str_head + "/" + str_tail;
	}
	if (regex_match(path, regex2))
		return "/";
	if (regex_match(path, regex1)) {
		return path;
	}
	string ans;
	for (int j = 0; j < path.length(); ++j) {
		if (path[j] != '/')
			ans += path[j];
		else
		{
			if (path[j + 1] != '/'&&j < path.length() - 1)
				ans += '/';
		}
	}
	if (ans[0] != '/')
		ans = '/' + ans;
	return ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值