class Solution {
    public String simplifyPath(String path) {
        if (path == null || path.length() == 0) {
            return path;
        }
        String[] clearStr = path.split("/");
        StringBuilder result = new StringBuilder();
        Stack<String> paths = new Stack<>();
        result.append('/');
        for (String str : clearStr) {
            if (str.equals("") || str.equals(".")) {
                continue;
            }
            
            if (str.equals("..")) {
                if (!paths.isEmpty()) {
                    paths.pop();;
                }
                continue;
            }
            paths.push(str);
        }
        
        while (!paths.isEmpty()) {
            result.insert(1, "/");
            result.insert(1, paths.pop());
        }
        
        return result.length() == 1 ? result.toString() : result.toString().substring(0, result.length() - 1);
    }
}

 

LOTS of EDGE CASES:

1. Root path, when we return, it needs to be checked.

2. When we meet "..", we shall check whether it is root path or not, but do not forget to skip pushing into stack.

posted on 2017-08-23 15:26  keepshuatishuati  阅读(100)  评论(0编辑  收藏  举报