leetcode71 简化路径 java实现

/**
注意点:字符串比较是否相等使用equals函数,不要使用==
Stack已经不被推荐使用,现在用Deque替代,双端队列
*/

class Solution {
    public String simplifyPath(String path) {
        String[] str = path.split("/");
        Deque<String> sta = new ArrayDeque<>();
        StringBuilder res = new StringBuilder();
        for(int i = 0;i<str.length;i++){
            if(str[i].equals(".") ||str[i].length()==0)continue;
            if(str[i].equals("..") && sta.size()==0)continue;
            if(str[i].equals("..") && sta.size()!=0){
                sta.pop();
            }else{
                sta.push(str[i]);
            }
        }
        if(sta.isEmpty())return "/";
        while(!sta.isEmpty()){
            res.insert(0,sta.pop());
            res.insert(0,"/");
        }
        return res.toString();
    }
}
posted @ 2020-12-10 23:40  void-white  阅读(81)  评论(0)    收藏  举报