码迷,mamicode.com
首页 > 其他好文 > 详细

Simplify Path

时间:2015-01-31 00:16:52      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:
  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes ‘/‘ together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

代码实现(未优化):

#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
    string simplifyPath(string path) {
		return SplitString(path,"/");
    }
	string SplitString(const string& s, const string& c)
	{
		stack<string>st;
		int pos2 = s.find(c);
		int pos1 = 0;
		while(string::npos != pos2)
		{
			string te = s.substr(pos1, pos2-pos1);
			
			if(te.length() > 0){
				
				if(te.compare("..") == 0){
					if(!st.empty())
						st.pop();
				}else if(te.compare(".") == 0){}
				else{
					st.push(te);
				}
			}
			pos1 = pos2 + c.size();
			pos2 = s.find(c, pos1);
		}
		if(pos1 != s.length()){
			string te = s.substr(pos1);
			if(te.compare("..") == 0){
				if(!st.empty())
					st.pop();
			}else if(te.compare(".") == 0){}
			else{
				st.push(te);
			}
		}
		string r = "";
		while(st.empty() == NULL){
			r =  "/" + st.top() + r ;
			st.pop();
		}
		if(r.compare("") == 0){
			r = "/";
		}
		return r;
	}
};
int main(){
	Solution s = Solution();
	string r = s.simplifyPath("///");
	cout << r << endl;
}

  

 

Simplify Path

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4263414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!