Leetcode71.Simplify_Path

将非/…与/.的部分记录,遇到/…则弹出一段路径(若栈为空则不做操作),遇到/.不做操作。最后整合字符串。若栈为空则返回’/’。
时间复杂度:O(N)
C++代码:

class Solution {
public:
	string simplifyPath(string path) {
		path.push_back('/');
		stack<string> record;
		auto it = path.begin();
		string temp = "/";
		while (it < path.end())
		{
			if (*it == '/')
			{
				if (temp != "/")
				{
					if (temp == "/..")
					{
						if (!record.empty())
							record.pop();
						temp.clear();
					}
					else if (temp == "/.")
						temp.clear();
					else
					{
						record.push(temp);
						temp.clear();
					}
					temp = "/";
				}
			}
			else
			{
				temp.push_back(*it);
			}
			it++;
		}
		string simpPath;
		while (!record.empty())
		{
			simpPath.insert(simpPath.begin(), record.top().begin(),record.top().end());
			record.pop();
		}
		if (simpPath.empty())
			return "/";
		return simpPath;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82954578
今日推荐