Exemplo n.º 1
1
  /**
   * Method to find the Euler Tour based on the Hierholzer's algorithm.
   *
   * @param g : Input graph for which the tour is to be found.
   * @return : Returns a list of edges that comprises of the Euler Tour.
   */
  public static List<Edge> findEulerTour(Graph<Vertex> g) {
    Vertex start = g.verts.get(1);
    Stack<Edge> forward = new Stack<Edge>();
    Stack<Edge> backtrack = new Stack<Edge>();
    Edge e = getUnvisitedEdge(start);
    while (e != null) {
      e.visited = true;
      forward.push(e);
      e = getUnvisitedEdge(e.To);
    }

    while (!(forward.isEmpty())) {
      e = forward.pop();
      backtrack.push(e);
      e = getUnvisitedEdge(e.From);
      while (e != null) {
        e.visited = true;
        forward.push(e);
        e = getUnvisitedEdge(e.To);
      }
    }

    List<Edge> path = new LinkedList<Edge>();
    while (!backtrack.isEmpty()) {
      Edge edge = backtrack.pop();
      path.add(edge);
    }
    return path;
  }
 public int maximalRectangle(char[][] matrix) {
   int m = matrix.length;
   if (m == 0) {
     return 0;
   }
   int n = matrix[0].length;
   int[][] height = new int[m][n + 1];
   for (int j = 0; j < n + 1; j++) {
     for (int i = 0; i < m; i++) {
       height[i][j] = 0;
     }
   }
   for (int j = 0; j < n; j++) {
     for (int i = 0; i < m; i++) {
       if (matrix[i][j] == '1') {
         height[i][j] = (i > 0 ? (height[i - 1][j] + 1) : 1);
       }
     }
   }
   int result = 0;
   for (int i = 0; i < m; i++) {
     Stack<Integer> stk = new Stack<Integer>();
     int j = 0;
     while (j < n + 1) {
       if (stk.isEmpty() || (height[i][stk.peek()] <= height[i][j])) {
         stk.push(j);
         j++;
       } else {
         int index = stk.pop();
         result = Math.max(result, height[i][index] * (stk.isEmpty() ? j : j - stk.peek() - 1));
       }
     }
   }
   return result;
 }
Exemplo n.º 3
0
  /**
   * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the
   * input string is valid.
   *
   * <p>The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and
   * "([)]" are not.
   */
  public static boolean isValid(String s) {
    int length = s.length();
    if (length == 0) {
      return true;
    }

    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < length; i++) {
      if (stack.isEmpty()) {
        char c = s.charAt(i);
        if (c == ')' || c == ']' || c == '}') {
          return false;
        }
        stack.add(s.charAt(i));
        continue;
      }
      char l = stack.peek();
      char r = s.charAt(i);
      if ((r == ')' && l == '(') || (r == ']' && l == '[') || (r == '}' && l == '{')) {
        stack.pop();
      } else {
        stack.push(r);
      }
    }
    return stack.isEmpty();
  }
Exemplo n.º 4
0
  public static boolean isValid(String s) {

    if (s.length() <= 1 || s.length() % 2 != 0) {
      return false;
    }
    HashMap<Character, Integer> table = new HashMap<Character, Integer>();
    Stack<Character> store = new Stack<Character>();
    table.put('(', 1);
    table.put(')', -1);
    table.put('[', 2);
    table.put(']', -2);
    table.put('{', 3);
    table.put('}', -3);

    for (int i = 0; i < s.length(); i++) {
      if (table.get(s.charAt(i)) > 0) {
        store.push(s.charAt(i));
      } else {
        if (!store.isEmpty() && table.get(store.pop()) + table.get(s.charAt(i)) != 0) {
          return false;
        }
      }
    }
    if (!store.isEmpty()) {
      return false;
    }
    return true;
  }
Exemplo n.º 5
0
 public boolean isValid(String s) {
   if (s == null || s.length() == 0) return true;
   Stack<Character> stack = new Stack<Character>();
   for (int i = 0; i < s.length(); i++) {
     char c = s.charAt(i);
     switch (c) {
       case '(':
       case '[':
       case '{':
         stack.push(c);
         break;
       case ')':
         if (!stack.isEmpty() && stack.peek() == '(') stack.pop();
         else return false;
         break;
       case ']':
         if (!stack.isEmpty() && stack.peek() == '[') stack.pop();
         else return false;
         break;
       case '}':
         if (!stack.isEmpty() && stack.peek() == '{') stack.pop();
         else return false;
         break;
       default:
         return false;
     }
   }
   return stack.isEmpty();
 }
 public static void flattenIterative1(TreeNode root) {
   Stack<TreeNode> stack = new Stack<>();
   while (root != null) {
     if (root.left != null) {
       stack.push(root);
       root = root.left;
     } else if (root.right != null) {
       stack.push(root);
       root = root.right;
     } else if (!stack.isEmpty()) {
       TreeNode end = root;
       while (!stack.isEmpty()
           && (stack.peek().left == null
               || (stack.peek().left != null && stack.peek().left != root))) {
         root = stack.pop();
       }
       if (stack.isEmpty()) root = root.right;
       else {
         TreeNode top = stack.peek();
         TreeNode temp = top.right;
         top.right = root;
         top.left = null;
         end.right = temp;
         root = (end.left != null || temp == null) ? end : temp;
       }
     } else root = root.right;
   }
 }
 @NotNull
 private static Collection<PsiLanguageInjectionHost> collectInjectionHosts(
     @NotNull PsiFile file, @NotNull TextRange range) {
   Stack<PsiElement> toProcess = new Stack<PsiElement>();
   for (PsiElement e = file.findElementAt(range.getStartOffset());
       e != null;
       e = e.getNextSibling()) {
     if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
       break;
     }
     toProcess.push(e);
   }
   if (toProcess.isEmpty()) {
     return Collections.emptySet();
   }
   Set<PsiLanguageInjectionHost> result = null;
   while (!toProcess.isEmpty()) {
     PsiElement e = toProcess.pop();
     if (e instanceof PsiLanguageInjectionHost) {
       if (result == null) {
         result = ContainerUtilRt.newHashSet();
       }
       result.add((PsiLanguageInjectionHost) e);
     } else {
       for (PsiElement child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
         if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
           break;
         }
         toProcess.push(child);
       }
     }
   }
   return result == null ? Collections.<PsiLanguageInjectionHost>emptySet() : result;
 }
  static ArrayList<Integer> postorderTraversal2(TreeNode root) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    if (root == null) return result;
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode p = root;
    HashSet<TreeNode> set = new HashSet<TreeNode>();
    while (p != null || (!stack.isEmpty())) {
      while (p != null) {
        stack.push(p);
        p = p.left;
      }
      if (!stack.isEmpty()) {
        p = stack.pop();
        if (!set.contains(p)) {
          set.add(p);
          stack.push(p);
          p = p.right;

        } else {
          result.add(p.val);
          p = null;
        }
      }
    }
    return result;
  }
Exemplo n.º 9
0
  /*
  如果能够确定每个节点的父亲节点,则可以构造出整棵树。找出每个数往左数第一个比他大的数和往右数第一个比他大的数,
  两者中较小的数即为该数的父亲节点。如:[3,1,2],3没有父亲节点,1的父亲节点为2,2的父亲节为3。
  并且可以根据与父亲的位置关系来确定是左儿子还是右儿子。接下来的问题是如何快速找出每个数往左、往右第一个比他大的数。
  这里需要用到数据结构栈。以找每个数左边第一个比他大的数为例,从左到右遍历每个数,栈中保持递减序列,
  新来的数不停的Pop出栈顶直到栈顶比新数大或没有数。以[3,1,2]为例,首先3入栈,接下来1比3小,无需pop出3,1入栈,
  并且确定了1往左第一个比他大的数为3。接下来2比1大,1出栈,2比3小,2入栈。并且确定了2往左第一个比他大的数为3。
  用同样的方法可以求得每个数往右第一个比他大的数。时间复杂度O(n),空间复杂度也是O(n)为最优解法。
   */
  public TreeNode maxTree(int[] A) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode root = null;
    stack.push(new TreeNode(A[0]));
    for (int i = 1; i < A.length; i++) {
      if (A[i] < stack.peek().val) {
        stack.push(new TreeNode(A[i]));
      } else {
        TreeNode node = stack.pop();
        while (!stack.isEmpty() && stack.peek().val < A[i]) {
          TreeNode tmp = stack.pop();
          tmp.right = node;
          node = tmp;
        }

        TreeNode newNode = new TreeNode(A[i]);
        newNode.left = node;
        stack.push(newNode);
      }
    }

    root = stack.pop();
    while (!stack.isEmpty()) {
      stack.peek().right = root;
      root = stack.pop();
    }

    return root;
  }
Exemplo n.º 10
0
  void start(XMLEntity entity) {
    if (LOG.isLoggable(Level.FINER)) {
      LOG.finer("Start of " + entity);
    }

    final boolean parentIncluded = (inclusionContext.isEmpty() ? true : inclusionContext.peek());
    inclusionContext.push(
        parentIncluded ? !configuration.excluded(entity) : configuration.included(entity));

    spacePreservationContext.push(
        spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek());
    final Object xmlSpace = entity.getAttributes().get(TextConstants.XML_SPACE_ATTR_NAME);
    if (xmlSpace != null) {
      spacePreservationContext.pop();
      spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString()));
    }

    nodePath.set(entity.getAttributes());
    nodePath.push(0);

    elementContext.push(entity);

    for (XMLTransformerModule<T> m : modules) {
      m.start(this, entity);
    }
  }
Exemplo n.º 11
0
  /**
   * convert infix to post polish expression operators follows operands. shunting (branching) yard
   * algorithm by Dijkastra http://en.wikipedia.org/wiki/Shunting-yard_algorithm
   *
   * @param input
   * @return
   */
  public static String infixToPostfix(String input) {
    Scanner scan = new Scanner(input + " $");
    Stack<Character> operators = new Stack<Character>();
    StringBuilder sb = new StringBuilder();
    while (true) {
      if (scan.hasNextDouble()) {
        sb.append(scan.nextDouble() + " ");
      } else if (scan.hasNext("[+-/*\\(\\)\\$]")) {
        char op = scan.next().charAt(0);
        while (!operators.isEmpty()
            && op != '('
            && getPrecedence(op) <= getPrecedence(operators.peek())) {
          sb.append(operators.pop() + " ");
        } // since ')' is lower than most of operators in terms of precedence.
        // here we guarantee all the operators enclosed in parentheses are output to the buffer.
        if (op == '$') {
          break;
        }
        if (op == ')') {
          operators.pop();
          continue;
        }
        operators.push(op);
      }
    }

    while (!operators.isEmpty()) {
      sb.append(operators.pop() + " ");
    }
    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
  }
  public static void main(String[] args) throws IOException {
    Scanner sc = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);

    int tc = sc.nextInt();
    sc.nextLine();
    while (tc-- > 0) {
      ArrayList<Character> syms = new ArrayList<Character>();
      while (true) {
        String line = sc.nextLine();
        if (line == null || line.isEmpty()) break;
        syms.add(line.charAt(0));
      }
      Stack<Character> ops = new Stack<Character>();
      StringBuilder sb = new StringBuilder();
      for (char c : syms)
        if (c >= '0' && c <= '9') sb.append(c);
        else {
          if (c == '(') ops.push(c);
          else {
            while (!ops.isEmpty() && ops.peek() != '(' && pr(c) <= pr(ops.peek()))
              sb.append(ops.pop());
            if (c == ')') ops.pop();
            else ops.push(c);
          }
        }
      while (!ops.isEmpty()) sb.append(ops.pop());
      out.println(sb);
      if (tc != 0) out.println();
    }
    out.flush();
    out.close();
  }
Exemplo n.º 13
0
  /** 判断两棵二å?‰æ ‘是å?¦ç›¸å?Œçš„树(迭代) é??历一é??å?³å?¯ï¼Œè¿™é‡Œç”¨preorder */
  public static boolean isSame(TreeNode r1, TreeNode r2) {
    // 如果两个树都是空树,则返回true
    if (r1 == null && r2 == null) {
      return true;
    }

    // 如果有一棵树是空树,�一颗�是,则返回false
    if (r1 == null || r2 == null) {
      return false;
    }

    Stack<TreeNode> s1 = new Stack<TreeNode>();
    Stack<TreeNode> s2 = new Stack<TreeNode>();

    s1.push(r1);
    s2.push(r2);

    while (!s1.isEmpty() && !s2.isEmpty()) {
      TreeNode n1 = s1.pop();
      TreeNode n2 = s2.pop();
      if (n1 == null && n2 == null) {
        continue;
      } else if (n1 != null && n2 != null && n1.val == n2.val) {
        s1.push(n1.right);
        s1.push(n1.left);
        s2.push(n2.right);
        s2.push(n2.left);
      } else {
        return false;
      }
    }
    return true;
  }
Exemplo n.º 14
0
  /** å?Žåº?é??历迭代解法 http://www.youtube.com/watch?v=hv-mJUs5mvU */
  public static void postorderTraversal(TreeNode root) {
    if (root == null) {
      return;
    }

    Stack<TreeNode> s =
        new Stack<TreeNode>(); // 第一个stack用于添加node和它的左�孩�
    Stack<TreeNode> output =
        new Stack<TreeNode>(); // 第二个stack用于翻转第一个stack输出

    s.push(root);
    while (!s.isEmpty()) { // 确�所有元素都被翻转转移到第二个stack
      TreeNode cur = s.pop(); // 把栈顶元素添加到第二个stack
      output.push(cur);

      if (cur.left
          != null) { // 把栈顶元素的左孩�和�孩�分别添加入第一个stack
        s.push(cur.left);
      }
      if (cur.right != null) {
        s.push(cur.right);
      }
    }

    while (!output.isEmpty()) { // é??历输出第二个stack,å?³ä¸ºå?Žåº?é??历
      System.out.print(output.pop().val + " ");
    }
  }
Exemplo n.º 15
0
  /**
   * Convert an arithmetic expression in infix notation (e.g 1+2) to postfix notation (e.g 12+) Only
   * simple expressions not containing brackets are supported. <br>
   * A description of the algorithm used to accomplish this task can be found at:
   * http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm <br>
   * Basically the list of {@code Tokens} is being scanned from left to right, all operands
   * (numbers) are pushed onto a {@code Stack}. If the {@code Token} is an operator it is compared
   * to the operator on top of the {@code Stack}. If the operator on top of the {@code Stack} has a
   * higher or equal weight than the current operator, the top of the {@code Stack} is pushed to the
   * postfix list. Therefore the operators with higher weight are going to be executed first when
   * the expression is evaluated. This process continues until the top of the {@code Stack} has a
   * lower weight than the current operator or the {@code Stack} is empty. Then the current operator
   * is pushed onto the {@code Stack}.
   *
   * @param tokenizer The {@code Tokenizer} which will be converted to postfix. It must not be
   *     {@code null}.
   * @return The resulting {@code List} of {@code Token}s in postfix order.
   */
  private static List<Token> postfix(Tokenizer tokenizer) {
    Stack<Token> stack = new Stack<>();
    List<Token> postfix = new LinkedList<>();
    BiPredicate<Token, Token> hasHigherOrEqualWeight =
        (t1, t2) ->
            Operators.getOpWeight(t1.getOperator()) - Operators.getOpWeight(t2.getOperator()) >= 0;

    while (tokenizer.hasNext()) {
      Token t = tokenizer.next();
      switch (t.getType()) {
        case NUMBER:
          postfix.add(t);
          break;
        case OPERATOR:
          if (!stack.isEmpty() && hasHigherOrEqualWeight.test(stack.peek(), t)) {
            while (!stack.isEmpty() && hasHigherOrEqualWeight.test(stack.peek(), t)) {
              postfix.add(stack.pop());
            }
            stack.push(t);
          } else {
            stack.push(t);
          }
          break;
        case OPENING_BRACKET:
        case CLOSING_BRACKET:
          throw new IllegalArgumentException(
              "Cannot create postfix expression if the source contains brackets.");
      }
    }

    while (!stack.isEmpty()) postfix.add(stack.pop());

    return postfix;
  }
Exemplo n.º 16
0
  private void computePermutations(int[] array) {
    if (array.length == 1) {
      List<Integer> permutation = new LinkedList<>(stack);
      permutation.add(array[0]);
      permutations.add(permutation);

      if (!stack.isEmpty()) {
        stack.pop();
      }
    } else {
      for (int i = 0; i < array.length; i++) {
        stack.push(array[i]);
        int[] newArray = new int[array.length - 1];
        int index = 0;

        for (int j = 0; j < array.length; j++) {
          if (i != j) {
            newArray[index] = array[j];
            index++;
          }
        }

        computePermutations(newArray);
      }

      if (!stack.isEmpty()) {
        stack.pop();
      }
    }
  }
Exemplo n.º 17
0
  public void sort() {
    if (stack.isEmpty()) {
      return;
    }

    helper.push(stack.pop());

    boolean sorted = false;
    while (!sorted) {
      while (!stack.isEmpty() && stack.peek() > helper.peek()) {
        helper.push(stack.pop());

        if (stack.isEmpty()) {
          while (!helper.isEmpty()) {
            stack.push(helper.pop());
          }
          sorted = true;
          break;
        }
      }
      if (!sorted) {
        int temp = stack.pop();
        while (!helper.isEmpty() && helper.peek() > temp) {
          stack.push(helper.pop());
        }
        helper.push(temp);
      }
    }
  }
 /**
  * Initialization method that has 3 different behaviors based on whether bookmark model is loaded.
  * If the bookmark model is not loaded yet, it pushes a loading state to backstack which contains
  * the url from preference. If the model is loaded and the backstack is empty, it creates a state
  * by fetching the last visited bookmark url stored in preference. If the bookmark model is loaded
  * but backstack contains a pending loading state, it creates a new state by getting the url of
  * the loading state and replace the previous loading state with the new normal state.
  */
 private void initializeIfBookmarkModelLoaded() {
   if (mEnhancedBookmarksModel.isBookmarkModelLoaded()) {
     mSearchView.onEnhancedBookmarkDelegateInitialized(this);
     mDrawerListView.onEnhancedBookmarkDelegateInitialized(this);
     mContentView.onEnhancedBookmarkDelegateInitialized(this);
     if (mStateStack.isEmpty()) {
       setState(UIState.createStateFromUrl(getUrlFromPreference(), mEnhancedBookmarksModel));
     } else if (mStateStack.peek().mState == UIState.STATE_LOADING) {
       String url = mStateStack.pop().mUrl;
       setState(UIState.createStateFromUrl(url, mEnhancedBookmarksModel));
     }
   } else {
     mContentView.showLoadingUi();
     mDrawerListView.showLoadingUi();
     mContentView.showLoadingUi();
     if (mStateStack.isEmpty() || mStateStack.peek().mState != UIState.STATE_LOADING) {
       setState(UIState.createLoadingState(getUrlFromPreference()));
     } else if (!mStateStack.isEmpty()) {
       // Refresh the UI. This is needed because on tablet, updateForUrl might set up
       // loading state too early and at that time all UI components are not created yet.
       // Therefore we need to set the previous loading state once again to trigger all UI
       // updates.
       setState(mStateStack.pop());
     }
   }
 }
  // if any ancestor node of given path is selected then unselect it
  //  and selection all its descendants except given path and descendants.
  // otherwise just unselect the given path
  private void toggleRemoveSelection(TreePath path) {
    Stack stack = new Stack();
    TreePath parent = path.getParentPath();
    while (parent != null && !isPathSelected(parent)) {
      stack.push(parent);
      parent = parent.getParentPath();
    }
    if (parent != null) stack.push(parent);
    else {
      super.removeSelectionPaths(new TreePath[] {path});
      return;
    }

    while (!stack.isEmpty()) {
      TreePath temp = (TreePath) stack.pop();
      TreePath peekPath = stack.isEmpty() ? path : (TreePath) stack.peek();
      Object node = temp.getLastPathComponent();
      Object peekNode = peekPath.getLastPathComponent();
      int childCount = model.getChildCount(node);
      for (int i = 0; i < childCount; i++) {
        Object childNode = model.getChild(node, i);
        if (childNode != peekNode)
          super.addSelectionPaths(new TreePath[] {temp.pathByAddingChild(childNode)});
      }
    }
    super.removeSelectionPaths(new TreePath[] {parent});
  }
Exemplo n.º 20
0
  public boolean isValid(String s) {
    if (s.length() == 1) {
      return false;
    }
    Map<Character, Character> map = new HashMap<Character, Character>();
    map.put('(', ')');
    map.put('[', ']');
    map.put('{', '}');
    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (map.containsKey(c) || stack.isEmpty() && map.containsKey(c)) {
        stack.push(c);
      } else if (map.containsValue(c)) {
        if (!stack.isEmpty() && map.get(stack.peek()) == c) {
          stack.pop();
        } else {
          return false;
        }
      }
    }

    if (stack.isEmpty()) {
      return true;
    } else {
      return false;
    }
  }
Exemplo n.º 21
0
 public String getRelativePath(SNode node)
     throws ArtifactsRelativePathHelper.RelativePathException {
   Stack<SNode> names = new Stack<SNode>();
   names.push(node);
   SNode parent = artifacts.parent(node);
   while (parent != null) {
     if (MapSequence.fromMap(prefixes).containsKey(parent)) {
       break;
     }
     names.push(parent);
     parent = artifacts.parent(parent);
   }
   if (parent == null) {
     throw new ArtifactsRelativePathHelper.RelativePathException("no common folder");
   }
   StringBuilder result = new StringBuilder(MapSequence.fromMap(prefixes).get(parent));
   while (!(names.isEmpty())) {
     SNode elem = names.pop();
     boolean lastElement = names.isEmpty();
     if (SNodeOperations.isInstanceOf(
         elem, "jetbrains.mps.build.structure.BuildLayout_TransparentContainer")) {
       continue;
     }
     result.append(getNodeName(elem, lastElement));
     if (!(lastElement)) {
       result.append("/");
     }
   }
   return result.toString();
 }
Exemplo n.º 22
0
 public boolean isValid(String s) {
   Stack<Character> stack = new Stack<Character>();
   for (char str : s.toCharArray()) {
     if (str == '(' || str == '[' || str == '{') {
       stack.push(str);
     } else if (str == ')') {
       if (!stack.isEmpty() && stack.peek() == '(') {
         stack.pop();
       } else {
         return false;
       }
     } else if (str == ']') {
       if (!stack.isEmpty() && stack.peek() == '[') {
         stack.pop();
       } else {
         return false;
       }
     } else if (str == '}') {
       if (!stack.isEmpty() && stack.peek() == '{') {
         stack.pop();
       } else {
         return false;
       }
     }
   }
   return stack.isEmpty();
 }
Exemplo n.º 23
0
  public static boolean isBalanced(String s) {
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      if (c == '{' || c == '[' || c == '(') stack.push(c);
      else if (c == '}') {
        if (!stack.isEmpty() && stack.peek() == '{') {
          stack.pop();
        } else return false;
      } else if (c == ']') {
        if (!stack.isEmpty() && stack.peek() == '[') {
          stack.pop();
        } else return false;
      } else if (c == ')') {
        if (!stack.isEmpty() && stack.peek() == '(') {
          stack.pop();
        } else return false;
      } else {

      }
    }

    return stack.isEmpty();
  }
Exemplo n.º 24
0
  /**
   * Restores a previously saved selection in the document.
   *
   * <p>If no selection was previously saved, nothing happens.
   *
   * @since 3.0
   */
  protected void restoreSelection() {

    if (!fSelections.isEmpty()) {

      final IDocument document = getDocument();
      final Position position = (Position) fSelections.pop();

      try {
        document.removePosition(fSelectionCategory, position);
        Point currentSelection = getSelectedRange();
        if (currentSelection == null
            || currentSelection.x != position.getOffset()
            || currentSelection.y != position.getLength()) {
          if (position instanceof ColumnPosition && getTextWidget().getBlockSelection()) {
            setSelection(
                new BlockTextSelection(
                    document,
                    document.getLineOfOffset(position.getOffset()),
                    ((ColumnPosition) position).fStartColumn,
                    document.getLineOfOffset(position.getOffset() + position.getLength()),
                    ((ColumnPosition) position).fEndColumn,
                    getTextWidget().getTabs()));
          } else {
            setSelectedRange(position.getOffset(), position.getLength());
          }
        }

        if (fSelections.isEmpty()) clearRememberedSelection();
      } catch (BadPositionCategoryException exception) {
        // Should not happen
      } catch (BadLocationException x) {
        // Should not happen
      }
    }
  }
Exemplo n.º 25
0
 private boolean contains2Words(Stack<String> stack) {
   String list_start = stack.pop(); // could be a LIST_START
   String word1 = stack.pop(); // token to analyze
   if (!stack.isEmpty()) {
     String word2 = stack.pop(); // token to analyze
     if (!stack.isEmpty() && stack.peek().equals(LIST_START)) {
       stack.push(word2);
       stack.push(word1);
       stack.push(list_start);
       if (isWord(word1) && isWord(word2)) {
         printOut("Contains TWO WORDS");
         return true;
       } else {
         return false;
       }
     } else {
       stack.push(word2);
       stack.push(word1);
       stack.push(list_start);
       return false;
     }
   }
   stack.push(word1);
   stack.push(list_start);
   return false;
 }
Exemplo n.º 26
0
  /** @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */
  public void processingInstruction(String target, String data) throws SAXException {
    if (inModification && charBuf.length() > 0) {
      final String normalized = charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);
      if (normalized.length() > 0) {
        final Text text = doc.createTextNode(normalized);
        if (stack.isEmpty()) {

          if (LOG.isDebugEnabled()) {
            LOG.debug("appending text to fragment: " + text.getData());
          }

          contents.add(text);
        } else {
          final Element last = stack.peek();
          last.appendChild(text);
        }
      }
      charBuf.setLength(0);
    }
    if (inModification) {
      final ProcessingInstruction pi = doc.createProcessingInstruction(target, data);
      if (stack.isEmpty()) {
        contents.add(pi);
      } else {
        final Element last = stack.peek();
        last.appendChild(pi);
      }
    }
  }
Exemplo n.º 27
0
 public boolean ignore() {
   if (ignoreStack.isEmpty()) {
     if (printNext.isEmpty()) return false;
     return !printNext.peek().booleanValue();
   }
   return ignoreStack.peek().booleanValue();
 }
Exemplo n.º 28
0
 /* (non-Javadoc)
  * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int)
  */
 public void comment(char[] ch, int start, int length) throws SAXException {
   if (inModification && charBuf.length() > 0) {
     final String normalized = charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);
     if (normalized.length() > 0) {
       final Text text = doc.createTextNode(normalized);
       if (stack.isEmpty()) {
         // LOG.debug("appending text to fragment: " + text.getData());
         contents.add(text);
       } else {
         final Element last = stack.peek();
         last.appendChild(text);
       }
     }
     charBuf.setLength(0);
   }
   if (inModification) {
     final Comment comment = doc.createComment(new String(ch, start, length));
     if (stack.isEmpty()) {
       contents.add(comment);
     } else {
       final Element last = stack.peek();
       last.appendChild(comment);
     }
   }
 }
Exemplo n.º 29
0
  public Geometry run() throws ProofFailureException {
    if (!geometries.isEmpty()) {
      try {
        init();
        Operation operator;
        Geometry rhs =
            geometries
                .pop(); // the far rhs of the geometry / the basis of the OperationalGeometry. Order
        // Shouldn't matter though
        while (!running_geometries.isEmpty()) {
          rhs = running_geometries.pop();
          if (!running_operations.isEmpty()) {
            operator = running_operations.pop();
            Geometry lhs = running_geometries.pop();
            Action a = actions.get(operator);
            rhs = a.act(lhs, rhs);
          } else
            throw new ProofFailureException("INTERNAL: Mismatched Operator and Geometry Tables");
        }

        flush();
        return rhs;

      } catch (GeometricFailure e) {
        throw new ProofFailureException("Inter");
      }
    } else throw new ProofFailureException("INTERNAL: This Machine Contains No Geometry.");
  }
  public int kthSmallest(TreeNode root, int k) {

    if (root == null) {
      return -1;
    }

    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode p = root;

    while (p != null || !stack.isEmpty()) {

      while (p != null) {
        stack.push(p);
        p = p.left;
      }

      if (!stack.isEmpty()) {
        p = stack.pop();
        if (--k == 0) {
          return p.val;
        }
        p = p.right;
      }
    }

    return 0;
  }