Simplify Path

几个corner cases要清楚

ref http://www.cnblogs.com/springfor/p/3869666.html

引用一个用法注意“ 判断字符串相等与否要用.equals(),因为是引用类型。

要注意split函数是可以split出空字符的,例如://b/ 会被split结果为["","b"]。

public class Solution {
    public String simplifyPath(String path) {
        if(path==null||path.length()==0) return path;
        String[] s = path.split("/");
        LinkedList<String> st = new LinkedList<String>();
        String res = new String();
        for(String tmp:s){
            //if(tmp.equals(".")||tmp.equals("/")){ 因为split已经去除多余的/了
            if(tmp.length()==0||tmp.equals(".")){
                continue;
            //}else if(tmp.equals("..")&&!st.isEmpty()){ //Input:    "/.."
             //   st.pop();
            }else if(tmp.equals("..")){
                if(!st.isEmpty())
                    st.pop();
            }else
                st.push(tmp);
        }
        if(st.isEmpty())
            return "/";
        while(!st.isEmpty()){
            res +="/" + st.removeLast();
        }
        return res;
        
    }
}

 

posted @ 2015-06-05 05:40  世界到处都是小星星  阅读(121)  评论(0编辑  收藏  举报