Simplify Path(Medium) 简化文件路径

Leetcode Source

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

For example,

path = "/home/", => "/home"

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

解题思路:

  1. 先把输入字符串以'/'为分隔符分来
  2. 处理:如果遇到'.'或者空输入什么都不做。如果遇到'..'就弹栈。 其它的情况就压栈。
  3. 组合出结果:每从栈里退出一个元素就用'/'连接起来,注意顺序。
 public static String simplifyPath(String path) {
        if(path.length() == 0){
            return path;
        }

        String[] splits = path.split("/");
        LinkedList<String> stack = new LinkedList<String>();
        for (String s : splits) {
            if(s.length()==0 || s.equals(".")){
                continue;
            }else if(s.equals("..")){
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }else{
                stack.push(s);
            }
        }

        if(stack.isEmpty()){
            stack.push("");
        }
        String ret = "";
        while(!stack.isEmpty()){
            ret += "/" + stack.removeLast();
        }

        return ret;
    }

results matching ""

    No results matching ""