Simplify Path

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

算法:根据/把path分割,再逐个判断

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");
        Stack<String> s = new Stack<String>();
        for(int i=0;i<strs.length;i++){
            if(strs[i].equals(".")){
            }else if(strs[i].equals("..")){
                if(!s.isEmpty())
                    s.pop();
            }else if(strs[i].length()>0){
                s.push(strs[i]);
            }
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = s.iterator();
        while(it.hasNext()){
            String t = it.next();
            sb.append("/").append(t);
        }
        String r=sb.toString();
        if(r.length()==0)
            r+="/";
        return r;
    }
}





posted @ 2014-11-24 22:36  bingtel  阅读(120)  评论(0编辑  收藏  举报