Java Code Examples for java.util.Deque#size()

The following examples show how to use java.util.Deque#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LongestAbsoluteFilePath.java    From LeetCode-Sol-Res with MIT License 6 votes vote down vote up
/**
 * Stack.
 * Using stack to save previous length at each level.
 * Find current level by the last index of "\t" in filename + 1.
 * Compare current level with stack size, stack size should be one level larger than current level.
 * Calculate current length, with slash at the end.
 * Push this length into stack.
 * If current name is a file, update max.
 * The length here should minus 1 to remove the last "/".
 */
public int lengthLongestPath(String input) {
  Deque<Integer> stack = new ArrayDeque<>();
  stack.push(0); // Dummy level, start from 0
  String[] files = input.split("\n");
  int max = 0;
  for (String f : files) {
    int level = f.lastIndexOf("\t") + 1;
    while (stack.size() > level + 1) { // Stack size is one level larger since we have a dummy level
      stack.pop();
    }
    int len = stack.peek() + f.length() - level + 1; // Previous length + current length + "/"
    stack.push(len);
    if (f.contains(".")) { // Update max only when it is a file
      max = Math.max(max, len - 1); // Length without the last "/"
    }
  }
  return max;
}
 
Example 2
Source File: TracingHandlerInterceptor.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
    Object handler, Exception ex) {

  if (!isTraced(httpServletRequest)) {
    return;
  }

  Span span = tracer.activeSpan();
  for (HandlerInterceptorSpanDecorator decorator : decorators) {
    decorator.onAfterCompletion(httpServletRequest, httpServletResponse, handler, ex, span);
  }
  Deque<Scope> scopeStack = getScopeStack(httpServletRequest);
  if(scopeStack.size() > 0) {
    Scope scope = scopeStack.pop();
    scope.close();
  }
  if (httpServletRequest.getAttribute(IS_ERROR_HANDLING_SPAN) != null) {
    httpServletRequest.removeAttribute(IS_ERROR_HANDLING_SPAN);
    span.finish();
  }
}
 
Example 3
Source File: VerifyPreorderSerializationOfABinaryTree.java    From LeetCode-Sol-Res with MIT License 6 votes vote down vote up
/**
 * Stack.
 * Iterate through the string characters.
 * If it's a number, just push to stack.
 * If it's a '#', we need to figure out some sub situations:
 * 1) If the top of the stack is a number, then this '#' is the left child, just push it.
 * 2) If the top of the stack is a '#', then this '#' is the right child, we should pop the subtree.
 * 2.1) After the subtree is popped, if the stack top is still '#', it means the subtree should be popped again.
 * 2.2) If the stack top is a number, we need to add a '#' to mark that the next node knows it's a right child.
 * https://discuss.leetcode.com/topic/35973/java-intuitive-22ms-solution-with-stack
 */
public boolean isValidSerialization(String preorder) {
  Deque<String> stack = new ArrayDeque<>();
  String[] nodes = preorder.split(",");
  for (int i = 0; i < nodes.length; i++) {
    String curr = nodes[i];
    while ("#".equals(curr) && !stack.isEmpty() && "#".equals(stack.peek())) {
      stack.pop();
      if (stack.isEmpty()) {
        return false;
      }
      stack.pop();
    }
    stack.push(curr);
  }
  return stack.size() == 1 && "#".equals(stack.peek());
}
 
Example 4
Source File: Solution.java    From DailyCodingProblem with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static int dfs(Deque<Node> path, Node node, int sum) {
    if (node == null)
        return Integer.MAX_VALUE;

    path.addLast(node);

    if (node.left == null && node.right == null)
        return sum + node.data;

    int size = path.size();
    int leftSum = dfs(path, node.left, sum + node.data);
    repair(path, size);
    int rightSum = dfs(path, node.right, sum + node.data);

    if (leftSum < rightSum) {
        repair(path, size);
        return dfs(path, node.left, sum + node.data);
    }

    return rightSum;
}
 
Example 5
Source File: BindingGraphValidator.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether the given dependency path would require the most recent request to be resolved
 * by only provision bindings.
 */
private boolean doesPathRequireProvisionOnly(Deque<ResolvedRequest> path) {
  if (path.size() == 1) {
    // if this is an entry-point, then we check the request
    switch (path.peek().request().kind()) {
      case INSTANCE:
      case PROVIDER:
      case LAZY:
      case MEMBERS_INJECTOR:
        return true;
      case PRODUCER:
      case PRODUCED:
      case FUTURE:
        return false;
      default:
        throw new AssertionError();
    }
  }
  // otherwise, the second-most-recent bindings determine whether the most recent one must be a
  // provision
  ImmutableSet<ProvisionBinding> dependentProvisions = provisionsDependingOnLatestRequest(path);
  return !dependentProvisions.isEmpty();
}
 
Example 6
Source File: PSSubCommand.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(final Deque<Double> stack, final double x) {
	if(stack.size() < 2) {
		throw new InvalidFormatPSFunctionException();
	}

	final double a = stack.pop();
	final double b = stack.pop();

	stack.push(b - a);
}
 
Example 7
Source File: Command.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected boolean acceptOption(Deque<String> options, String expected) throws UserSyntaxException {
    if (expected.equals(options.peek())) {
        if (options.size() < 2) {
            throw new UserSyntaxException("missing value for " + options.peek());
        }
        options.remove();
        return true;
    }
    return false;
}
 
Example 8
Source File: ConditionBuilder.java    From Despector with MIT License 5 votes vote down vote up
private static void dfs(ConditionGraphNode next, Deque<Condition> stack) {

        // performs a depth-first-search to populate each node in the graph's
        // partial conditions

        if (!stack.isEmpty()) {
            // Add the condition up to this point to the partial conditions of
            // this node. This represents a path from the root to this node and
            // the condition of that path is the and of all simple conditions of
            // the nodes along the path
            if (stack.size() == 1) {
                next.addPartialCondition(stack.peek());
            } else {
                Condition partial = new AndCondition(stack);
                next.addPartialCondition(partial);
            }
        }
        if (next.getSimpleCondition() == null) {
            return;
        }
        // Push the simple condition of this node to the stack and recurse into
        // the target branch
        stack.addLast(next.getSimpleCondition());
        dfs(next.getTarget(), stack);
        stack.pollLast();
        // Same thing for the else_target except we push the inverse of this
        // node's condition
        stack.addLast(inverse(next.getSimpleCondition()));
        dfs(next.getElseTarget(), stack);
        stack.pollLast();
    }
 
Example 9
Source File: CalcitePrepare.java    From Quicksql with MIT License 5 votes vote down vote up
public static void push(Context context) {
  final Deque<Context> stack = THREAD_CONTEXT_STACK.get();
  final List<String> path = context.getObjectPath();
  if (path != null) {
    for (Context context1 : stack) {
      final List<String> path1 = context1.getObjectPath();
      if (path.equals(path1)) {
        throw new CyclicDefinitionException(stack.size(), path);
      }
    }
  }
  stack.push(context);
}
 
Example 10
Source File: AbstractFileReporter.java    From revapi with Apache License 2.0 5 votes vote down vote up
/**
 * @return a comparator that can be used to sort the reports in the order of the compared elements.
 */
protected Comparator<Report> getReportsByElementOrderComparator() {
    return (r1, r2) -> {
        Element r1El = r1.getOldElement() == null ? r1.getNewElement() : r1.getOldElement();
        Element r2El = r2.getOldElement() == null ? r2.getNewElement() : r2.getOldElement();

        Deque<Element> r1Ancestry = new ArrayDeque<>();
        Deque<Element> r2Ancestry = new ArrayDeque<>();

        while (r1El != null) {
            r1Ancestry.push(r1El);
            r1El = r1El.getParent();
        }

        while (r2El != null) {
            r2Ancestry.push(r2El);
            r2El = r2El.getParent();
        }

        while (!r1Ancestry.isEmpty() && !r2Ancestry.isEmpty()) {
            int order = r1Ancestry.pop().compareTo(r2Ancestry.pop());
            if (order != 0) {
                return order;
            }
        }

        return r1Ancestry.size() - r2Ancestry.size();
    };
}
 
Example 11
Source File: Solution.java    From DailyCodingProblem with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Deque<Integer> interleave(Deque<Integer> stack) {
    Queue<Integer> queue = new LinkedList<>();

    for (int i = stack.size() - 1; i > 1; i--) {
        for (int j = 0; j < i; j++)
            queue.add(stack.pop());

        for (int j = 0; j < i; j++)
            stack.push(queue.remove());
    }

    return stack;
}
 
Example 12
Source File: Sub103.java    From spring-boot-demo with MIT License 5 votes vote down vote up
List<List<Integer>> BFS(TreeNode root) {
    Deque<TreeNode> deque = new LinkedList<>();
    deque.addLast(root);
    List<List<Integer>> result = new LinkedList<>();
    boolean reverse = true;
    while (!deque.isEmpty()) {
        int size = deque.size();
        List<Integer> subResult = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node;
            if (reverse) {
                //头出
                node = deque.pollFirst();

                //尾进
                if (node.left != null) {
                    deque.addLast(node.left);
                }
                if (node.right != null) {
                    deque.addLast(node.right);
                }
            } else {
                //尾出
                node = deque.pollLast();

                //头进
                if (node.right != null) {
                    deque.addFirst(node.right);
                }
                if (node.left != null) {
                    deque.addFirst(node.left);
                }
            }
            subResult.add(node.val);
        }
        result.add(subResult);
        reverse = !reverse;
    }
    return result;
}
 
Example 13
Source File: PSExchCommand.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(final Deque<Double> stack, final double x) {
	if(stack.size() < 2) {
		throw new InvalidFormatPSFunctionException();
	}

	final Double a = stack.pop();
	final Double b = stack.pop();

	stack.push(a);
	stack.push(b);
}
 
Example 14
Source File: Solution116.java    From LeetCodeSolution with Apache License 2.0 5 votes vote down vote up
/**
 * 1.About Complexity
 *     1.1 Time Complexity is O(n)
 *     1.2 Space Complexity is O(1)
 * 2.how I solve
 *     2.1 this solution is base on level order
 *     2.2 define a queue(cache all node),a list(cache node from each floor),a integer(cache current queue size),a node(cache last circulation node)
 *     2.3 get all node from queue and put them to list
 *     2.4 circulate to get list's element
 *          2.4.1 add children(right children first,left children last) to queue
 *          2.4.2 judge whether i is 0
 *                  2.4.2.1 i=0,set lastNode to current node
 *                  2.4.2.2 i!=0,set current node.next to lastNode and lastNode to temp
 *     2.5 clear list and make lastNode to null
 * 3.About submit record
 *     3.1 1ms and 35.4MB memory in LeetCode China
 *     3.2 1ms and 36.1MB memory in LeetCode
 * 4.Q&A
 * @param root
 * @return
 */
public Node connectByLevelOrder(Node root) {
    if(root==null){
        return root;
    }
    Deque<Node> queue=new LinkedList<>();
    List<Node> list=new ArrayList<>();
    Node lastNode=null;
    int size;
    queue.offerLast(root);
    while(queue.size()!=0){
        size=queue.size();
        for(int i=0;i<size;i++){
            list.add(queue.pollFirst());
        }
        for(int i=0;i<list.size();i++){
            Node temp=list.get(i);
            if(temp.right!=null){
                queue.offerLast(temp.right);
            }
            if(temp.left!=null){
                queue.offerLast(temp.left);
            }
            if(i==0){
                lastNode=temp;
            }
            else{
                temp.next=lastNode;
                lastNode=temp;
            }
        }
        lastNode=null;
        list.clear();
    }
    return root;
}
 
Example 15
Source File: Command.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
final protected void ensureMinArgumentCount(Deque<String> options, int minCount) throws UserSyntaxException {
    if (options.size() < minCount) {
        throw new UserSyntaxException("too few arguments");
    }
}
 
Example 16
Source File: AbstractFragmentProvider.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public String getFragment(final EObject object, final Fallback fallback) {
  final Deque<EObject> containingObjects = new ArrayDeque<>();
  EObject current = object;
  while (current != null) {
    containingObjects.push(current);
    current = current.eContainer();
  }
  if (containingObjects.peek().eResource() == null) {
    // could happen while unloading objects
    return fallback.getFragment(object);
  }
  final StringBuilder result = new StringBuilder(containingObjects.size() * FRAGMENT_BUFFER_CAPACITY);
  StringBuilder previousSegment = new StringBuilder(FRAGMENT_BUFFER_CAPACITY);
  StringBuilder segment = new StringBuilder(FRAGMENT_BUFFER_CAPACITY);
  internalAppendFragmentSegment(containingObjects.pop(), segment);
  int reps = 1;
  result.append(SEGMENT_SEPARATOR);
  result.append(segment);
  while (!containingObjects.isEmpty()) {
    StringBuilder temp = previousSegment;
    previousSegment = segment;
    segment = temp;
    segment.setLength(0);
    internalAppendFragmentSegment(containingObjects.pop(), segment);
    if (equal(previousSegment, segment)) {
      reps++;
    } else {
      if (reps == 2 && previousSegment.length() == 1) {
        result.append(SEGMENT_SEPARATOR).append(previousSegment);
        reps = 1;
      } else if (reps > 1) {
        result.append(REP_SEPARATOR).append(reps);
        reps = 1;
      }
      result.append(SEGMENT_SEPARATOR).append(segment);
    }
  }
  if (reps == 2 && previousSegment.length() == 1) {
    result.append(SEGMENT_SEPARATOR).append(previousSegment);
  } else if (reps > 1) {
    result.append(REP_SEPARATOR).append(reps);
  }
  return result.toString();
}
 
Example 17
Source File: ChainInventoryMsgHandler.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void processMessage(PeerConnection peer, GSCMessage msg) throws P2pException {

    ChainInventoryMessage chainInventoryMessage = (ChainInventoryMessage) msg;

    check(peer, chainInventoryMessage);

    peer.setNeedSyncFromPeer(true);

    peer.setSyncChainRequested(null); //todo thread sec

    Deque<BlockId> blockIdWeGet = new LinkedList<>(chainInventoryMessage.getBlockIds());

    if (blockIdWeGet.size() == 1 && gscNetDelegate.containBlock(blockIdWeGet.peek())) {
        peer.setNeedSyncFromPeer(false);
        return;
    }

    while (!peer.getSyncBlockToFetch().isEmpty()) {
        if (peer.getSyncBlockToFetch().peekLast().equals(blockIdWeGet.peekFirst())) {
            break;
        }
        peer.getSyncBlockToFetch().pollLast();
    }

    blockIdWeGet.poll();

    peer.setRemainNum(chainInventoryMessage.getRemainNum());
    peer.getSyncBlockToFetch().addAll(blockIdWeGet);

    synchronized (gscNetDelegate.getBlockLock()) {
        while (!peer.getSyncBlockToFetch().isEmpty() && gscNetDelegate
                .containBlock(peer.getSyncBlockToFetch().peek())) {
            BlockId blockId = peer.getSyncBlockToFetch().pop();
            peer.setBlockBothHave(blockId);
            logger.info("Block {} from {} is processed", blockId.getString(), peer.getNode().getHost());
        }
    }

    //if (chainInventoryMessage.getRemainNum() == 0 && peer.getSyncBlockToFetch().isEmpty()) {
    //  peer.setNeedSyncFromPeer(false);
    //}

    if ((chainInventoryMessage.getRemainNum() == 0 && !peer.getSyncBlockToFetch().isEmpty()) ||
            (chainInventoryMessage.getRemainNum() != 0
                    && peer.getSyncBlockToFetch().size() > NodeConstant.SYNC_FETCH_BATCH_NUM)) {
        syncService.setFetchFlag(true);
    } else {
        syncService.syncNext(peer);
    }
}
 
Example 18
Source File: TagExpressionParser.java    From cucumber with MIT License 4 votes vote down vote up
private Expression parse() {	
    List<String> tokens = tokenize(infix);
    if(tokens.isEmpty()) return new True();

    Deque<String> operators = new ArrayDeque<>();
    Deque<Expression> expressions = new ArrayDeque<>();
    TokenType expectedTokenType = TokenType.OPERAND;
    for (String token : tokens) {
        if (isUnary(token)) {
            check(expectedTokenType, TokenType.OPERAND);
            operators.push(token);
            expectedTokenType = TokenType.OPERAND;
        } else if (isBinary(token)) {
            check(expectedTokenType, TokenType.OPERATOR);
            while (operators.size() > 0 && isOperator(operators.peek()) && (
                    (ASSOC.get(token) == Assoc.LEFT && PREC.get(token) <= PREC.get(operators.peek()))
                            ||
                            (ASSOC.get(token) == Assoc.RIGHT && PREC.get(token) < PREC.get(operators.peek())))
                    ) {
                pushExpr(pop(operators), expressions);
            }
            operators.push(token);
            expectedTokenType = TokenType.OPERAND;
        } else if ("(".equals(token)) {
            check(expectedTokenType, TokenType.OPERAND);
            operators.push(token);
            expectedTokenType = TokenType.OPERAND;
        } else if (")".equals(token)) {
            check(expectedTokenType, TokenType.OPERATOR);
            while (operators.size() > 0 && !"(".equals(operators.peek())) {
                pushExpr(pop(operators), expressions);
            }
            if (operators.size() == 0) {
                throw new TagExpressionException("Tag expression '%s' could not be parsed because of syntax error: unmatched )", this.infix);
            }
            if ("(".equals(operators.peek())) {
                pop(operators);
            }
            expectedTokenType = TokenType.OPERATOR;
        } else {
            check(expectedTokenType, TokenType.OPERAND);
            pushExpr(token, expressions);
            expectedTokenType = TokenType.OPERATOR;
        }
    }

    while (operators.size() > 0) {
        if ("(".equals(operators.peek())) {
            throw new TagExpressionException("Tag expression '%s' could not be parsed because of syntax error: unmatched (", infix);
        }
        pushExpr(pop(operators), expressions);
    }

    return expressions.pop();
}
 
Example 19
Source File: Examiner.java    From visualee with Apache License 2.0 4 votes vote down vote up
protected static String scanAfterClosedParenthesis(String currentToken, Scanner scanner) {
   int countParenthesisOpen = countChar(currentToken, '(');
   int countParenthesisClose = countChar(currentToken, ')');

   if (countParenthesisOpen == countParenthesisClose) {
      return scanner.next();
   }

   Deque<Integer> stack = new ArrayDeque<>();
   for (int iCount = 0; iCount < countParenthesisOpen - countParenthesisClose; iCount++) {
      stack.push(1);
   }
   if (!scanner.hasNext()) {
      throw new IllegalArgumentException("Insufficient number of tokens to scan after closed parenthesis in token " + currentToken);
   }
   String token = scanner.next();

   whilestack:
   do {
      for (Examiner examiner : JavaSourceInspector.getInstance().getExaminers()) {
         if (examiner.getTypeFromToken(token) != null) {
            break whilestack;
         }
      }
      if (token.indexOf('(') > -1) {
         int countOpenParenthesis = countChar(token, '(');
         for (int iCount = 0; iCount < countOpenParenthesis; iCount++) {
            stack.push(1);
         }
      }
      if (token.indexOf(')') > -1) {
         int countClosedParenthesis = countChar(token, ')');
         for (int iCount = 0; iCount < countClosedParenthesis; iCount++) {
            stack.pop();
         }
      }
      if (scanner.hasNext()) {
         token = scanner.next();
      } else {
         break;
      }
   } while (stack.size() > 0);

   return token;
}
 
Example 20
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 4 votes vote down vote up
private Map<String, Plugin> resolveRecursiveDependencies(Plugin plugin, @CheckForNull Map<String, Plugin> topLevelDependencies) {
    Deque<Plugin> queue = new LinkedList<>();
    Map<String, Plugin> recursiveDependencies = new HashMap<>();
    queue.add(plugin);
    recursiveDependencies.put(plugin.getName(), plugin);

    while (queue.size() != 0) {
        Plugin dependency = queue.poll();

        if (!dependency.isDependenciesSpecified()) {
            dependency.setDependencies(resolveDirectDependencies(dependency));
        }

        for (Plugin p : dependency.getDependencies()) {
            String dependencyName = p.getName();
            Plugin pinnedPlugin = topLevelDependencies != null ? topLevelDependencies.get(dependencyName) : null;

            // See https://github.com/jenkinsci/plugin-installation-manager-tool/pull/102
            if (pinnedPlugin != null) { // There is a top-level plugin with the same ID
                if (pinnedPlugin.getVersion().isNewerThanOrEqualTo(p.getVersion())) {
                    if (verbose) {
                        logVerbose(String.format("Skipping dependency %s:%s and its sub-dependencies, because there is a higher version defined on the top level - %s:%s",
                                p.getName(), p.getVersion(), pinnedPlugin.getName(), pinnedPlugin.getVersion()));
                    }
                    continue;
                } else {
                    String message = String.format("Plugin %s:%s depends on %s:%s, but there is an older version defined on the top level - %s:%s",
                            plugin.getName(), plugin.getVersion(), p.getName(), p.getVersion(), pinnedPlugin.getName(), pinnedPlugin.getVersion());
                    // TODO(oleg_nenashev): Should be an error by default, but it is not how the tests are written now
                    // throw new PluginDependencyStrategyException(message);
                    logVerbose(message);
                }
            }

            if (!recursiveDependencies.containsKey(dependencyName)) {
                recursiveDependencies.put(dependencyName, p);
                queue.add(p);
            } else {
                Plugin existingDependency = recursiveDependencies.get(dependencyName);
                if (existingDependency.getVersion().isOlderThan(p.getVersion())) {
                    outputPluginReplacementInfo(existingDependency, p);
                    queue.add(p); //in case the higher version contains dependencies the lower version didn't have
                    recursiveDependencies.replace(dependencyName, existingDependency, p);
                }
            }
        }
    }
    return recursiveDependencies;
}