71. 簡化路徑

這個題目主要考察棧的用法:

public static String simplifyPath(String path) {

        if(path == null || path.isEmpty()){
            return "/";
        }
        Stack<String> stack = new Stack<>();
        String[] split = path.split("/");
        int length = split.length;
        for(int i =0; i < length; i++){
            String str = split[i];
            if("".equals(str) || ".".equals(str)){
                continue;
            }else if("..".equals(str)){
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }else{
                stack.push(str);
            }
        }
        
        if(stack.isEmpty()){
            return "/";
        }

        Iterator<String> iterator = stack.iterator();
        StringBuilder sb = new StringBuilder();

        while (iterator.hasNext()){
            String rest = iterator.next();
            sb.append("/").append(rest);
        }

        return sb.toString();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章