Using Java Deque


  • 0
    A
    public String simplifyPath(final String path) {
            String[] pathElements = path.trim().split("/");
            Deque<Integer> validIndices = new LinkedList<>();
    
            for (int i = 0; i < pathElements.length; i++) {
                String pathElement = pathElements[i];
                if (pathElement.isEmpty() || pathElement.equals(".")){
                    continue;
                } else if (pathElement.equals("..")) {
                    if (!validIndices.isEmpty()) {
                        validIndices.removeLast();
                    }
                } else {
                    validIndices.addLast(i);
                }
            }
    
            StringBuffer result = new StringBuffer();
            while (!validIndices.isEmpty()) {
                result.append("/" + pathElements[validIndices.removeFirst()]);
            }
    
            return result.length() == 0 ? "/" : result.toString();
        }
    

Log in to reply
 

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