071 Simplify Path 简化路径

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
边界情况:
    你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回"/"。
    此外,路径中也可能包含多个斜杠'/',如 "/home//foo/"。
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo"。
详见:https://leetcode.com/problems/simplify-path/description/

Java实现:

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stk=new Stack<String>();
        String[] strs=path.split("/");
        for(String str:strs){
            if(!stk.isEmpty()&&str.equals("..")){
                stk.pop();
            }else if(!str.equals(".")&&!str.equals("")&&!str.equals("..")){
                stk.push(str);
            }
        }
        List<String> res=new ArrayList(stk);
        return "/"+String.join("/",res);
    }
}

 C++实现:

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> stack;
		int i = 0;
		while (i < path.size()) {
			// 跳过斜线'/'
			while (i < path.size() && '/' == path[i])
            {
                ++i;
            }
			// 记录路径名
			string s = "";
			while (i < path.size() && path[i] != '/')
            {
                s += path[i++];
            }
			// 如果是".."则需要弹栈,否则入栈
			if (".." == s && !stack.empty())
            {
                stack.pop();
            }
			else if ("" != s&&s != "."&&s != "..")
            {
                stack.push(s);
            }
		}
		// 如果栈为空,说明为根目录,只有斜线'/'
		if (stack.empty())
        {
            return "/";
        }
		// 逐个连接栈里的路径名
		string s = "";
		while (!stack.empty())
		{
			s = "/" + stack.top() + s;
			stack.pop();
		}
		return s;
    }
};
原文地址:https://www.cnblogs.com/xidian2014/p/8708127.html