Java Solution Using Deque


  • 1
    D
        public String simplifyPath(String path) {
            if (path == null || path.length() == 0) {return new String();}
            path = path.trim();
            Deque<String> q = new LinkedList<>();
            for (String s : path.split("/")) {
                if (s.equals("..")) {
                    if (!q.isEmpty()) {
                        q.pollLast();
                    }
                } 
                else if (!s.equals(".") && !s.equals("")) {
                    q.offerLast(s);
                }
            }
            
            StringBuilder sb = new StringBuilder();
            while (!q.isEmpty()) {
                sb.append("/").append(q.pollFirst());
            }
            return sb.length() == 0 ? new String("/") : sb.toString();
        }

Log in to reply
 

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