December 23, 2019

71. Simplify Path

71. Simplify Path

用 stack, Time = O(n), space = O(n)

class Solution {
    public String simplifyPath(String path) {
        Deque<String> stack = new ArrayDeque<>();
        String[] p = path.split("/");
        for (String s : p) {
            if (s.equals("") || s.equals(".")) {
                continue;
            } else if (s.equals("..")) {
                stack.pollFirst();
            } else {
                stack.offerFirst(s);
            }
        }
        if (stack.isEmpty()) {
            return "/";
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.insert(0, stack.pollFirst());
            sb.insert(0, "/");
        }
        return sb.toString();
    }
}
comments powered by Disqus