其他分享
首页 > 其他分享> > 71. Simplify Path

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
    }

 

标签:String,res,equals,stk,substring,Simplify,71,path,Path
来源: https://www.cnblogs.com/feiflytech/p/15863890.html