Java Solution


  • 1
    U
    public class Solution {
        public String simplifyPath(String path) {
            if (path == null || path.length()==0) return new String();
            path=path.trim();
            Deque<String> stack = new LinkedList<>();
            Set<String> set = new HashSet<>(Arrays.asList("","..","."));
            
            for(String dir : path.split("/")){
                if(dir.equals("..") && !stack.isEmpty()) stack.pollLast();
                else if(!set.contains(dir)) stack.offerLast(dir);
            }
            
            StringBuilder res = new StringBuilder();
            
            while(!stack.isEmpty()){
                res.append("/").append(stack.pollFirst());
            }
            return res.length()==0 ?new String("/"):res.toString();
            
        }
    }
    

Log in to reply
 

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