LeetCode-Simplify Path-路径简化-栈的应用

https://oj.leetcode.com/problems/simplify-path/

这道题很简答。就是用栈把有效目录名存起来,然后根据后面解析出的..进行出栈操作。

主要麻烦在于解析路径,解析从p开始的下一个目录名,我的做法如下:

1)首先跳过所有开头的'/',这里不小心写了一个死循环,距离bug-free的代码还很远。

2)找到下一个'/',如果找不到就将下次当做结尾,然后substr。

最后结束时将栈里的东西组合起来就行了。

class Solution {
public:
	int n,m;
	string path;
	int Next(int p,string &s){
		while (p<path.length()){
			if (path[p]=='/'){
				p++;
			}
			else{break;}
		}
		if (p==path.length()){return p;}
		size_t q=path.find('/',p);
		if (q==string::npos){
			s=path.substr(p,path.length()-p);
			return path.length();
		}
		s=path.substr(p,q-p);
		return q;
	}
	string simplifyPath(string path) {
		n=path.length();
		this->path=path;
		int p=0;
		vector <string> st;
		while (p<n){
			string s;
			p=Next(p,s);
			if (s.length()==0){continue;}
			if (s=="."){continue;}
			if (s==".."){
				if (!st.empty()){st.pop_back();}
				continue;
			}
			st.push_back(s);
		}
		string res="/";
		for (int i=0;i<st.size();i++){
			res+=st[i];
			if (i<st.size()-1){
				res+="/";
			}
		}
		return res;
	}
};

  

转载于:https://www.cnblogs.com/yangsc/p/4007188.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值