5/31/2020

[LeetCode] 71. Simplify Path

Problem : https://leetcode.com/problems/simplify-path/


class Solution {
    public String simplifyPath(String path) {
        Deque<String> deque = new LinkedList<>();
        StringBuilder token = new StringBuilder();
        
        if (path.charAt(path.length()-1) != '/') {
            path += "/";
        }
        
        for (char c : path.toCharArray()) {
            if (c == '/') {
                if ( ".".equals(token.toString()) || token.length() == 0) {
                    // do nothing
                } else if ("..".equals(token.toString())) {
                    if (!deque.isEmpty()) {
                        deque.pollLast();
                    }
                } else {
                    deque.offerLast(token.toString());
                }
                // reset the token 
                token.setLength(0);
            } else {
                token.append(c);
            }
        }
        
        StringBuilder result = new StringBuilder();
        
        while (!deque.isEmpty()) {
            result.append("/");
            result.append(deque.pollFirst());
        }
        
        return result.length() != 0 ? result.toString() : "/";      
    }
}

Edited on 03/13/2022. Use deque to push / pop from the rear and pop in the front of the intermediate 'directory name' list.

No comments:

Post a Comment