When we met path or parentheses problems, always think about Stack first.

For this problem, only three conditions need to be considered:

1. the substring is ".."

2. the substring is "."

3. the substring is "" 

    public String simplifyPath(String path) {
        Stack<String> stk = new Stack<>();
        String[] strs = path.split("/");
        for(String s: strs){
            if(s.equals("..")){
                if(!stk.isEmpty())
                    stk.pop();
            }
            else if(!s.equals("")&&!s.equals("."))  //if the substring is empty or ".", it should be ignored.
                stk.push(s);
        }
        
        StringBuilder res = new StringBuilder();
        for(String s: stk){
            res.append('/');
            res.append(s);
        }
        return res.length()==0?"/": res.toString();  //Don't forget to check whether the string is empty
    }

 

posted on 2022-02-05 09:54  阳光明媚的菲越  阅读(27)  评论(0编辑  收藏  举报