Advertisement
LeatherDeer

Untitled

Dec 4th, 2022
568
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. class MyQueue {
  2.    
  3.     Stack<Integer> in;
  4.     Stack<Integer> out;
  5.    
  6.     public MyQueue() {
  7.         in = new Stack<>();
  8.         out = new Stack<>();
  9.     }
  10.    
  11.     public void push(int x) {
  12.         in.push(x);
  13.     }
  14.    
  15.     public int pop() {
  16.         if (out.isEmpty()) {
  17.             while (!in.isEmpty()) {
  18.             out.add(in.pop());
  19.             }    
  20.         }
  21.         return out.pop();
  22.     }
  23.    
  24.     public int peek() {
  25.         if (out.isEmpty()) {
  26.             while (!in.isEmpty()) {
  27.             out.add(in.pop());
  28.             }    
  29.         }
  30.          
  31.        
  32.         return out.peek();
  33.     }
  34.    
  35.     public boolean empty() {
  36.         return in.isEmpty() && out.isEmpty();
  37.     }
  38. }
  39.  
  40. class Solution {
  41.     public String simplifyPath(String path) {
  42.         Deque<String> deq = new LinkedList<>();
  43.         String[] tokens = path.split("/");
  44.         for (var token : tokens) {
  45.             if ("..".equals(token)) {
  46.                 if (!deq.isEmpty()) {
  47.                     deq.pollLast();
  48.                 }
  49.             } else if (!"".equals(token) && !".".equals(token)) {
  50.                 deq.addLast(token);
  51.             }
  52.         }
  53.         if (deq.isEmpty()) {
  54.             return "/";
  55.         }
  56.  
  57.         StringBuilder ans = new StringBuilder();
  58.         while (!deq.isEmpty()) {
  59.             ans.append("/").append(deq.pollFirst());
  60.         }
  61.  
  62.         return ans.toString();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement