71. Simplify Path

Leetcode Diary

Posted by Xudong on December 18, 2020

Problem Description

Thoughts

  • 把path split 成一个个子路径
  • 使用一个stack 遍历所有的路径
    • 当子路径为.和空时,不进栈
    • 当子路径为..时,pop出上一层路径
  • 最后再从bottomtop遍历栈,把路径拼装回去
public String simplifyPath(String path) {
    String[]paths = path.split("/");
    Stack<String> s = new Stack<String>();
    for(String dir : paths) {
        if(dir.equals(".") || dir.isEmpty())
            continue;
        if(dir.equals("..")) {
            if(!s.isEmpty())
                s.pop();
        }
        else
            s.push(dir);
    }
    StringBuilder res = new StringBuilder();
    for(String dir : s) {
        res.append("/");
        res.append(dir);
    }
    return res.length() == 0 ? "/" : res.toString();
}