Fork me on GitHub

71. Simplify Path

71. Simplify Path

题目

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".

解析

这道题的要求是简化一个Unix风格下的文件的绝对路径。

字符串处理,由于".."是返回上级目录(如果是根目录则不处理),因此可以考虑用栈记录路径名,以便于处理。需要注意几个细节:

重复连续出现的'/',只按1个处理,即跳过重复连续出现的'/';
如果路径名是".",则不处理;
如果路径名是"..",则需要弹栈,如果栈为空,则不做处理;
如果路径名为其他字符串,入栈。

最后,再逐个取出栈中元素(即已保存的路径名),用'/'分隔并连接起来,不过要注意顺序呦。

时间复杂度:O(n); 空间复杂度:O(n)

  • 或者在if(s[i]!='/')下面考虑问题,就不存在末尾为空字符串的情况
class Solution_71 {
public:

	// test:"/a/./b///../c/../././../d/..//../e/./f/./g/././//.//h///././/..///" output:"/e/f/g"
	string simplifyPath(string path) {

		stack<string> st;
		for (int i = 0; i < path.size();i++)
		{
			while (i < path.size() && path[i] == '/') i++;  //可能多个

			string str = "";
			while (i<path.size()&&path[i]!='/')  //记录'/'之间的字符串
			{
				str += path[i];
				i++;
			}
			if (str == ".")
			{
				continue;
			}
			if (str==".."&&!st.empty())
			{
				st.pop();
			}
			else if (str!=".."&&str!="") //必须有啊   /.. ; ///斜杆在末尾的时候str=""
			{
				st.push(str);
			}
		}
		string ret = "";
		if (st.empty())
		{
			return "/";
		}
		while (!st.empty())
		{
			ret = "/" + st.top()+ret; //加在后面,否则逆序
			st.pop();
		}

		return ret;
	}

};

题目来源

posted @ 2018-03-27 12:45  ranjiewen  阅读(170)  评论(0编辑  收藏  举报