力扣71.简化路经

题目:biubiu
题意:根据题意处理一个字符串。
我使用的栈进行处理,后面的子串有可能对前面的子串产生影响,可以使用栈先进后出的特性。然后进行遍历处理相应的情况。
注意: 使用栈,当你面对其中一种情况需要判断前一个子串也就是栈头元素时,一定要考虑栈是否为空,对栈中元素进行一个预判,防止空栈进行元素操作。
代码:

#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
	string simplifyPath(string path) {
		stack<string>p;
		string str;
		p.push("/");
		for (int i = 0; i < path.size(); i++) {
			str.erase(0);
			if (path[i] == '/') {
				if (i == path.size() - 1)
					continue;
				str.append(1, path[i]);
				if (p.size() == 0) {///注意
					p.push(str);
					continue;
				}
				if (p.top() == "/")
					continue;
				else
					p.push(str);
			}
			else if (path[i] == '.') {
				for (int j = i; j < path.size() && path[j] != '/'; j++) {
					str.append(1, path[j]);
					i = j;
				}
				if (str.size() == 1) {
					continue;
				}
				else if (str.size() == 2) {
					p.pop();
					if (p.size()) {
						p.pop();
					}
				}
				else {
					p.push(str);
				}
			}
			else {
				for (int j = i; j < path.size() && path[j] != '/'; j++) {
					str.append(1, path[j]);
					i = j;
				}
				p.push(str);
			}
		}
		str.erase(0);
		if (p.size() == 0) {
			str = "/";
			return str;
		}
		while (p.size()) {///注意
			if (p.top() == "/")
				p.pop();
			else
				break;
		}
		while (p.size()) {
			str.insert(0, p.top());
			p.pop();
		}
		if (str.size() == 0)
			str.insert(0, 1, '/');
		return str;
	}
};

int main() {
	string path;
	while (cin >> path) {
		Solution s;
		cout << s.simplifyPath(path) << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赟家小菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值