71. Simplify Path

来源:互联网 发布:新手怎么做淘宝分销 编辑:程序博客网 时间:2024/05/29 19:07

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

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

只需要设置对/.. /. 和 / 的判断即可

public class Solution {    public String simplifyPath(String path) {        Stack<String> stack = new Stack<String>();        Set<String> set = new HashSet<String>();        set.add(".");        set.add("..");        set.add("");        for(String s : path.split("/")){            if(s.equals("..")&& !stack.isEmpty()){                stack.pop();            }else if(!set.contains(s)) stack.push(s);        }        String res = "";        while(!stack.isEmpty()){            res = "/" + stack.pop() + res;        }        return res.isEmpty() ? "/" : res;    }}