Simplify Path

来源:互联网 发布:java项目添加log日志 编辑:程序博客网 时间:2024/06/05 02:08

熟悉数据结构,linkedlist stack, string.split 等等

public class Solution {    public String simplifyPath(String path) {        // ref http://www.cnblogs.com/springfor/p/3869666.html        if(path == null || path.length()==0)            return path;        String [] sp = path.split("/");        LinkedList<String> stack = new LinkedList<String>();               for(String s: sp ){            if(s.length()==0||s.equals("."))                continue;            if(s.equals("..")){                if(!stack.isEmpty())                    stack.pop();            }else                 stack.push(s);        }                if(stack.isEmpty())  // 处理“/” 有了这行,出来的才是“/”  否则就是“”            stack.push("");                    String res = new String();        while(!stack.isEmpty()){            res += "/" + stack.removeLast();        }                return res;    }}


0 0
原创粉丝点击