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;
	}
};

  

posted @ 2014-10-05 17:16  zombies  阅读(137)  评论(0编辑  收藏  举报