AC Solution in Java


  • 6
    L
    public class Solution {
        public String simplifyPath(String path) {
            Set<String> isSkip = new HashSet<>(Arrays.asList("", ".", ".."));
            Deque<String> stack = new ArrayDeque<>();
            for (String token : path.split("/")) {
                if (token.equals("..") && !stack.isEmpty()) stack.pop();
                if (isSkip.contains(token)) continue;
                stack.push(token);
            }
            StringBuilder sb = new StringBuilder();
            while (!stack.isEmpty()) {
                sb.append("/" + stack.pollLast());
            }
            return sb.length() == 0 ? "/" : sb.toString();
        }
    }

  • 0
    A

    I tried doing stack.pop() instead of stack.pollLast like how you did but it gives me the wrong answer. I thought pop() and pollLast() tecnically represent the same functionality. How are they different....?


  • 0
    L

    ArrayDeque behaves a little unexpected in this case.

    stack.push(1); stack.push(2) would internally be [2, 1]

    pop() removes the first item, i.e. 2 whereas pollLast() removes the last item, i.e. 1.

    Hope it helps.


  • 0
    B

    why is ".." necessary in isSkip?


  • 0
    L

    It is in there because it is already processed by the line before it. So as a way to simplify code, I put it in. It is actually not necessary to be there.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.