71. Simplify Path

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack=new Stack<String>();
        String[] strs=path.split("\\/");
        for(int i=0;i<strs.length;i++)
        {
            if(strs[i].length()==0||strs[i].equals("."))
                continue;
            else if(strs[i].equals(".."))
            {
                if(!stack.isEmpty())
                    stack.pop();
            }
            else
                stack.push(strs[i]);
        }
        StringBuilder sb=new StringBuilder();
        while(!stack.isEmpty())
            sb.insert(0, "/"+stack.pop());
        return sb.length()==0?"/":sb.toString();
    }
}

 

posted @ 2017-09-26 06:27  Weiyu Wang  阅读(126)  评论(0)    收藏  举报