Friday, August 18, 2017

71. Simplify Path

Version #1 Stack
二刷
两个点
1. escape -> \\
2. edge case是最后如果没有东西需要返回一个'/'
13.61 %
class Solution {
    public String simplifyPath(String path) {
        if (path == null || path.length() == 0) {
            return path;
        }
        String[] dirs = path.split("\\/+");
        StringBuilder sb = new StringBuilder();
        Deque<String> stack = new ArrayDeque<>();
        for (String dir : dirs) {
            if (dir.length() == 0 || dir.equals(".")) {
                continue;
            }
            if (dir.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.removeFirst();
                }
            } else {
                stack.addFirst(dir);
            }
        }
        while (!stack.isEmpty()) {
            sb.append("/" + stack.removeLast());
        }
        return sb.length() == 0 ? "/" : sb.toString();
    }
}

一刷
一开始写错了
最后stack里面剩下的元素应该倒序输出出来
所以把stack换成了deque
注意deque的API是pollLast()而不是popxx
看了discuss里面deque也可以用LinkedList实现
写成Deque<String> stack = new LinkedList<>();
中间照常用push 和pop
最后直接用for traverse LinkedList

73.48 %
class Solution {
    public String simplifyPath(String path) {
        if (path == null || path.length() == 0) return "/";
        String[] strs = path.trim().split("/");
        Deque<String> deque = new ArrayDeque<>();
        for (String str : strs) {
            if (str.equals(".") || str.equals("")) continue;
            if (str.equals("..")) {
                if (deque.isEmpty()) continue;
                deque.pollFirst();
            } else {
                deque.offerFirst(str);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!deque.isEmpty()) {
            sb.append("/");
            sb.append(deque.pollLast());
        }
        if (sb.length() < 1) return "/";
        else return sb.toString();
    }
}

No comments:

Post a Comment