Java Solution Using Deque


  • 0
    S

    Split the Path by "/" helps to deal with "//" edge cases
    Use deque as stack to deal with "/.." case where you need to delete previous layer,
    Use deque as queue to poll everything into a String.

    There is a wired case where "/.." expected "/" not "/.." Anyway, I comment it adding an else sentence.

    public class Solution {
        public String simplifyPath(String path) {
            String s = "/";
            String[] gross = path.split("/");
            Deque<Integer> deque = new LinkedList<Integer>();
            for(int i = 0;i < gross.length;i++){
                if(gross[i].equals(".") || gross[i].equals("")){continue;}
                else if(gross[i].equals("..")){
                    if(!deque.isEmpty())
                        deque.pollLast();
                    // add below if "/.." returns "/.."
                    // else
                    //     deque.offerLast(i);
                }else{
                    deque.offerLast(i);
                }
            }
            while(!deque.isEmpty()){
                s += gross[deque.pollFirst()];
                if(!deque.isEmpty())
                    s += "/";
            }
            return s;
        }
    }

  • 0
    J

    shouldn't set Deque type as String instead of Integer?


Log in to reply
 

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