71. Simplify Path

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
    }

 

上一篇:如何让机器客服更像人类客服?


下一篇:vue系统总结2