关闭

71. Simplify Path

标签: c++
89人阅读 评论(0) 收藏 举报
分类:

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

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

click to show corner cases.

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".
题意:精简路径信息。

思路:用栈实现。

class Solution {
public:
	string simplifyPath(string path) {
		stack<string> mystack;

		int p = 0;
		while (path[p] == '/'){
			p++;
		}
		if (p == path.size())
			return "/";
		path = path.substr(p);

		string s = spilt(path, '/');
		while (!s.empty()){
			if (s.compare(".") == 0){
				//do nothing
				
			}
			else if (s.compare("..") == 0){
				if (!mystack.empty())
					mystack.pop();
			}
			else
				mystack.push(s);

			int p = 0;
			while (path[p] == '/'){
				p++;
			}
			path = path.substr(p);
			s = spilt(path, '/');
		}
		if (mystack.empty()){
			return "/";
		}
		vector<string> simp(mystack.size());
		for (int i = 0; i < simp.size(); i++){
			simp[i] = mystack.top();
			mystack.pop();
		}
		string res;
		for (int i = simp.size()-1; i >= 0; i--){
			res += "/" + simp[i];
		}
		return res;
	}
	string spilt(string& path, char ch){
		string s;
		int i;
		int size = path.size();
		for (i = 0; i < path.size(); i++){
			char c = path[i];
			if (c == ch){
				s = path.substr(0, i);
				path = path.substr(i + 1);
				break;
			}
		}
		if (i == size){
			s = path;
			path.clear();
		}
		return s;
	}
};







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:41032次
    • 积分:2677
    • 等级:
    • 排名:第14370名
    • 原创:241篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条