Esempio 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 evalRPN(String[] strs) {
   if (strs == null) return 0;
   Stack<Integer> stack = new Stack<>();
   for (int i = 0; i < strs.length; i++) {
     if (strs[i].equals("+")
         || strs[i].equals("-")
         || strs[i].equals("*")
         || strs[i].equals("/")) {
       if (stack.size() < 2) return -1;
       if (strs[i].equals("+")) {
         stack.push(stack.pop() + stack.pop());
       } else if (strs[i].equals("-")) {
         stack.push(-stack.pop() + stack.pop());
       } else if (strs[i].equals("*")) {
         stack.push(stack.pop() * stack.pop());
       } else if (strs[i].equals("/")) {
         int a = stack.pop();
         int b = stack.pop();
         stack.push(b / a);
       }
     } else {
       stack.push(Integer.parseInt(strs[i]));
     }
   }
   return stack.pop();
 }
Esempio n. 3
0
  public static boolean umpadi(Stack s) {
    byte[] topElmt = ((Entry) s.peek()).getPart();
    byte[] oldTopElmt = topElmt;

    if (ByteMeth.endsWith(topElmt, Constant.umpadi)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "umpadi");
      s.pop();
      s.push(new Entry(Constant.pati, Tag.ParticleSuffix));
      s.push(new Entry(Constant.um, Tag.ThirdFutureNeuterSingularORRP));
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.umpadi.length);
      if (ByteMeth.isEqual(topElmt, Constant.kEtk)) {
        topElmt = ByteMeth.replace(topElmt, Constant.L, 2);
      }
      if (ByteMeth.endsWith(topElmt, Constant.var) || ByteMeth.endsWith(topElmt, Constant.thar)) {
        topElmt = ByteMeth.replace(topElmt, Constant.A, Constant.ar.length);
      }
      if (ByteMeth.isEqual(topElmt, Constant.kaRk)
          || ByteMeth.isEqual(topElmt, Constant.viRk)
          || ByteMeth.isEqual(topElmt, Constant.n_iRk)) {
        topElmt = ByteMeth.replace(topElmt, Constant.l, 2);
      }
      if (ByteMeth.isEqual(topElmt, Constant.sAk) || ByteMeth.isEqual(topElmt, Constant.pOk)) {
        topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - 1);
      }
      s.push(new Entry(topElmt, -1, oldTopElmt));
      Sandhi.kk(s);
      Sandhi.check(s);
      return true;
    }

    return false;
  }
Esempio n. 4
0
  public static boolean adverbial_Particle(Stack s) {
    byte[] topElmt = ((Entry) s.peek()).getPart();
    byte[] oldTopElmt = topElmt;

    // kayil
    if (ByteMeth.endsWith(topElmt, Constant.kayil)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "kayil");
      s.pop();
      s.push(new Entry(Constant.kayil, Tag.ParticleSuffix)); // change
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.kayil.length);
      s.push(new Entry(topElmt, -1, oldTopElmt));
      Sandhi.k(s);
      return true;
    }
    // poothu
    if (ByteMeth.endsWith(topElmt, Constant.poothu)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "poothu");
      s.pop();
      s.push(new Entry(Constant.poothu, Tag.ParticleSuffix)); // change
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.poothu.length);
      s.push(new Entry(topElmt, -1, oldTopElmt));
      Sandhi.k(s);
      return true;
    }

    return false;
  }
Esempio n. 5
0
  public static void main(String[] args)
      throws fullQueueException, EmptyQueueException, FullStackException {
    Main main = new Main();
    System.out.println(
        main.maximum(new Student("ali", 12), new Student("zohre", 10), new Student("ali", 18)));

    Stack<Student> stack1 = new Stack<>();
    stack1.push(new Student("ali", 15));
    stack1.push(new Student("samira", 12));

    System.out.println(stack1.pop());

    Stack<Student> stack2 = new Stack<>();
    stack2.push(new Student("ali", 15));
    stack2.push(new Student("samira", 12));
    System.out.println(stack2.pop());

    boolean result = stack1.equals(new Stack<Double>());
    System.out.println(result);

    Queue<Student> queue = new Queue<>();
    queue.push(new Student("ali", 15));
    queue.push(new Student("samira", 12));
    System.out.println(queue.pop());
  }
Esempio n. 6
0
  public void printSolution() {
    String currState = "www0bbb";
    File file = new File("solution_slidingtile_dfs.txt");
    try {
      FileWriter fw = new FileWriter(file);
      path.push(currState);
      while (parentMap.get(currState) != null) {
        // System.out.println("inside while, parentMap.get(currState)!=null");
        path.push(parentMap.get(currState));
        currState = parentMap.get(currState);
      }
      System.out.println("Solution path:");

      while (!path.empty()) {
        // System.out.println("inside while, stack not empty");
        // System.out.println(path.pop());
        fw.write(path.pop());
        fw.write("\n");
      }
      fw.close();
    } catch (IOException ie) {
      ie.printStackTrace();
    } finally {

    }
  }
 @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;
 }
Esempio n. 8
0
	private void dfs(Digraph G ,int v){
		onStack[v] = true ; 
		marked[v] = true ; 
		for(int w:G.adj(v)) 

		if(this.hasCycle()) {

		}
		if(!marked[v]){
				edgeTo[w] = v;
				dfs(G,w);
			}
		else{
			if(onStack[w]){
				cycle = new Stack<Integer>();
				for(int x = v; x!=w;x =edgeTo[x]) cycle.push(x);
				cycle.push(w);
				cycle.push(v);
			}
		} 

		onStack[v] = false;

		
	}
Esempio n. 9
0
 public static void createNgramsFromFolder(
     File input_folder, File output_folder, int ngram_value) {
   Stack<File> stack = new Stack<File>();
   stack.push(input_folder);
   while (!stack.isEmpty()) {
     File child = stack.pop();
     if (child.isDirectory()) {
       for (File f : child.listFiles()) stack.push(f);
     } else if (child.isFile()) {
       try {
         System.out.println("Processing: " + child.getAbsolutePath());
         FileReader fr = new FileReader(child.getAbsolutePath());
         FileWriter outputFile = new FileWriter(output_folder + "/file" + file_no);
         BufferedReader br = new BufferedReader(fr);
         String readline = "";
         while ((readline = br.readLine()) != null) {
           String[] words = readline.split("\\s+");
           for (int i = 0; i < words.length - ngram_value + 1; i++) {
             String ngram = "";
             for (int j = 0; j < ngram_value; j++) ngram = ngram + " " + words[i + j];
             outputFile.write(ngram + "\n");
           }
         }
         file_no++;
         outputFile.close();
         br.close();
         fr.close();
       } catch (Exception e) {
         System.out.println("File not found:" + e);
       }
     }
   }
 }
 /**
  * Returns type converted to index type if needed. A index type variable in java splitter file has
  * type "int" or "int[]" instead of "long" or "long[]". This is needed if the variable or the an
  * element of the variable is used as an index to an array. This method converts the type of the
  * variable to "int_index" or "index[]" if it is used as an index to an array or an element of it
  * is used as an index to an array.
  *
  * @param type the original type of the variable.
  * @param name the name of the variable.
  * @param varInfo the VarInfo of the variable.
  * @param condition the condition in which the variable occurs.
  * @return the type converted to index type if needed.
  */
 private static String makeIndexIfNeeded(
     String type, String name, VarInfo varInfo, String condition) throws ParseException {
   if ((type.equals("int") || varInfo.type.isArray())
       && varInfo.file_rep_type != ProglangType.HASHCODE) {
     int LPAREN = 74;
     int RPAREN = 75;
     int LBRACKET = 78;
     int RBRACKET = 79;
     Stack<Boolean> inArrayIndex = new Stack<Boolean>();
     inArrayIndex.push(Boolean.FALSE);
     NodeToken[] tokens = TokenExtractor.extractTokens(condition);
     for (int i = 0; i < tokens.length; i++) {
       if (tokens[i].kind == LBRACKET) {
         inArrayIndex.push(Boolean.TRUE);
       } else if (tokens[i].kind == RBRACKET) {
         inArrayIndex.pop();
       } else if (tokens[i].kind == LPAREN) {
         inArrayIndex.push(Boolean.FALSE);
       } else if (tokens[i].kind == RPAREN) {
         inArrayIndex.pop();
       } else if (inArrayIndex.peek().booleanValue() && tokens[i].tokenImage.equals(name)) {
         if (type.equals("int") || type.equals("int_index")) {
           // Note the type can only equal "int_index" if the variable
           // was already visited by this if statement since it appears
           // more than once in the condition.
           type = "int_index";
         } else {
           type = "index[]";
         }
       }
     }
     return type;
   }
   return type;
 }
Esempio n. 11
0
 /* 145 */
 public List<Integer> postorderTraversal(TreeNode root) {
   List<Integer> res = new LinkedList<Integer>();
   if (root == null) return res;
   Stack<TreeNode> stack = new Stack<TreeNode>();
   stack.push(root);
   TreeNode prev = null;
   while (!stack.isEmpty()) {
     TreeNode cur = stack.peek();
     if (prev == null || prev.left == cur || prev.right == cur) {
       if (cur.left != null) stack.push(cur.left);
       else if (cur.right != null) stack.push(cur.right);
       else {
         res.add(cur.val);
         stack.pop();
       }
     } else if (cur.left == prev) {
       if (cur.right != null) stack.push(cur.right);
       else {
         res.add(cur.val);
         stack.pop();
       }
     } else if (cur.right == prev) {
       res.add(cur.val);
       stack.pop();
     }
     prev = cur;
   }
   return res;
 }
  /**
   * The if...else... statements have been used to concentrate on the Interpreter pattern. A better
   * approach would be to use a separate pattern to hande each token such as that defined in Chain
   * of Responsibility.
   */
  public City evaluate(String route) {
    // Define the syntax tree
    Stack<Expression> expressionStack = new Stack<Expression>();

    // Parse each token in route string
    for (String token : route.split(" ")) {
      // Is token a recognised city?
      if (cities.containsKey(token)) {
        City city = cities.get(token);
        expressionStack.push(new CityExpression(city));

        // Is token to find most northerly?
      } else if (token.equals("northerly")) {
        expressionStack.push(new MostNortherlyExpression(loadExpressions(expressionStack)));

        // Is token to find most southerly?
      } else if (token.equals("southerly")) {
        expressionStack.push(new MostSoutherlyExpression(loadExpressions(expressionStack)));

        // Is token to find most westerly?
      } else if (token.equals("westerly")) {
        expressionStack.push(new MostWesterlyExpression(loadExpressions(expressionStack)));

        // Is token to find most easterly?
      } else if (token.equals("easterly")) {
        expressionStack.push(new MostEasterlyExpression(loadExpressions(expressionStack)));
      }
    }

    // Resulting value
    return expressionStack.pop().interpret();
  }
Esempio n. 13
0
  /**
   * 创建新的buffer,保存老的buffer。
   *
   * @throws IllegalStateException 如果不在buffer模式,或<code>getWriter</code> 方法曾被调用,或<code>
   *     getOutputStream</code>方法从未被调用
   */
  public void pushBuffer() {
    if (!buffering) {
      throw new IllegalStateException("Buffering mode is required to pushBuffer");
    }

    if (stream == null && writer == null) {
      throw new IllegalStateException(
          "getOutputStream() or getWriter() method has not been called yet");
    }

    flushBufferAdapter();

    // 向stream或writer stack中压入新的buffer。
    if (stream != null) {
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();

      bytesStack.push(bytes);

      ((BufferedServletOutputStream) stream).updateOutputStream(bytesStack.peek());

      logger.logMessage(
          LogLevel.DEBUG, "Pushed new byte buffer (stack size is " + bytesStack.size() + ")");
    } else {
      StringWriter chars = new StringWriter();

      charsStack.push(chars);

      ((BufferedServletWriter) writer).updateWriter(charsStack.peek());

      logger.logMessage(
          LogLevel.DEBUG, "Pushed new character buffer (stack size is " + charsStack.size() + ")");
    }
  }
  public int cal(String input) throws SyntaxErrorException {
    // initiates the empty stack
    operands = new Stack<Integer>();
    // tokenizes the input by space
    String[] tokens = input.split("\\s+");

    try {
      for (String eachToken : tokens) {
        char first = eachToken.charAt(0);
        if (Character.isDigit(first)) {
          int value = Integer.parseInt(eachToken);
          operands.push(value);
        } else if (isOperator(first)) {
          int result = calOps(first);
          operands.push(result);
        } else {
          throw new SyntaxErrorException("Invalid character ! " + first);
        }
      } // end of for loop

      // the case of no more tokens - pop result from stack
      int answer = operands.pop();
      if (operands.empty()) {
        return answer;
      } else {
        throw new SyntaxErrorException("Stack is not empty...");
      }
    } catch (EmptyStackException ex) {
      throw new SyntaxErrorException("It attempts to pop the empty stack .. ");
    }
  }
Esempio n. 15
0
  // DFS - stack
  public boolean validTree(int n, int[][] edges) {
    List<Set<Integer>> graph = new ArrayList<Set<Integer>>();
    for (int i = 0; i < n; i++) {
      graph.add(new HashSet<Integer>());
    }
    for (int[] edge : edges) {
      graph.get(edge[0]).add(edge[1]);
      graph.get(edge[1]).add(edge[0]);
    }

    boolean[] visited = new boolean[n];
    Stack<Integer> q = new Stack<Integer>();
    q.push(0);
    while (!q.isEmpty()) {
      int node = q.pop();
      if (visited[node]) return false;
      visited[node] = true;
      for (int neis : graph.get(node)) {
        graph.get(neis).remove(node);
        q.push(neis);
      }
    }
    for (boolean i : visited) {
      if (!i) return false;
    }
    return true;
  }
Esempio n. 16
0
  private CellSet seedFillOld(Cell seed, char newChar) {
    CellSet cellsFilled = new CellSet();
    char oldChar = get(seed);

    if (oldChar == newChar) return cellsFilled;
    if (isOutOfBounds(seed)) return cellsFilled;

    Stack<Cell> stack = new Stack<Cell>();

    stack.push(seed);

    while (!stack.isEmpty()) {
      Cell cell = stack.pop();

      set(cell, newChar);
      cellsFilled.add(cell);

      Cell nCell = cell.getNorth();
      Cell sCell = cell.getSouth();
      Cell eCell = cell.getEast();
      Cell wCell = cell.getWest();

      if (get(nCell) == oldChar) stack.push(nCell);
      if (get(sCell) == oldChar) stack.push(sCell);
      if (get(eCell) == oldChar) stack.push(eCell);
      if (get(wCell) == oldChar) stack.push(wCell);
    }

    return cellsFilled;
  }
Esempio n. 17
0
  // check that algorithm computes either the topological order or finds a directed cycle
  private void dfs(EdgeWeightedDigraph G, int v) {
    onStack[v] = true;
    marked[v] = true;
    for (DirectedEdge e : G.adj(v)) {
      int w = e.to();

      // short circuit if directed cycle found
      if (cycle != null) return;

      // found new vertex, so recur
      else if (!marked[w]) {
        edgeTo[w] = e;
        dfs(G, w);
      }

      // trace back directed cycle
      else if (onStack[w]) {
        cycle = new Stack<DirectedEdge>();
        while (e.from() != w) {
          cycle.push(e);
          e = edgeTo[e.from()];
        }
        cycle.push(e);
      }
    }

    onStack[v] = false;
  }
  public static void main(String[] args) {
    Stack s = new Stack();
    s.push(1);
    s.push(2);
    s.push(3);
    assert (s.peek().equals(3));
    s.pop();
    assert (s.peek().equals(2));
    s.pop();
    s.push(4);
    assert (s.peek().equals(4));
    s.pop();
    s.pop();
    try {
      s.pop();
    } catch (Exception e) {
      System.out.println("empty stack");
      System.out.println(e.getMessage());
    }

    Queue q = new Queue();
    q.enqueue(1);
    q.enqueue(2);
    assert (q.head().equals(1));
    q.dequeue();
    assert (q.head().equals(2));
    q.dequeue();
    try {
      q.dequeue();
    } catch (Exception e) {
      System.out.println("empty queue");
      System.out.println(e.getMessage());
    }
  }
Esempio n. 19
0
  // check that algorithm computes either the topological order or finds a directed cycle
  private void dfs(Digraph G, int v) {
    onStack[v] = true;
    marked[v] = true;
    for (int w : G.adj(v)) {

      // short circuit if directed cycle found
      if (cycle != null) return;

      // found new vertex, so recur
      else if (!marked[w]) {
        edgeTo[w] = v;
        dfs(G, w);
      }

      // trace back directed cycle
      else if (onStack[w]) {
        cycle = new Stack<Integer>();
        for (int x = v; x != w; x = edgeTo[x]) {
          cycle.push(x);
        }
        cycle.push(w);
        cycle.push(v);
      }
    }

    onStack[v] = false;
  }
  private void opStack(String operator) {
    // Push operator into the stack if it is empty
    if (opStack.empty()) {
      opStack.push(operator);
      return;
    }

    // Push operator into the stack if it is a left bracket
    if ("(".equals(operator)) {
      opStack.push(operator);
      return;
    }

    // Pop all elements in the stack to the output if meet the right bracket
    if (")".equals(operator)) {
      String tmp = "";
      while (!"(".equals(tmp = opStack.pop())) {
        postfixExpression.add(tmp);
      }
      return;
    }

    // Push any operator into the stack if the previous operator is left bracket
    if ("(".equals(opStack.peek())) {
      opStack.push(operator);
      return;
    }

    if (comparePriority(operator, opStack.peek())) {
      opStack.push(operator);
      return;
    }
  }
  /**
   * find a solution to the initial board (using the A* algorithm). Result will be stored in
   * searchNodeSolution queue;
   *
   * @param initial
   */
  public Solver(Board initial) {
    SearchNode initSearchNd = new SearchNode(initial, null);
    initialBoard = initial;
    pq.insert(initSearchNd);

    // output
    System.out.println("======Original SearchBoard==========");
    outputSN(initSearchNd);

    // find the Goal SearchNode
    while (!pq.min().board.isGoal()) {
      Stack<SearchNode> stackSNforNbrs = new Stack<SearchNode>();
      System.out.println("======NextLevel SearchBoard==========");

      // Insert all neighbors in the priority queue
      stackSNforNbrs = findNbrSearchNode(pq.delMin());
      while (stackSNforNbrs.size() != 0) {
        pq.insert(stackSNforNbrs.pop());
      }
    }

    // Trace back the search node
    SearchNode snInSolution = pq.min();
    Stack<SearchNode> stacksolution = new Stack<SearchNode>();
    while (snInSolution.prevNode != null) {
      stacksolution.push(snInSolution);
      snInSolution = snInSolution.prevNode;
    }
    stacksolution.push(initSearchNd);

    // Make it reverse order
    while (!stacksolution.isEmpty()) searchNodeSolution.enqueue(stacksolution.pop());
  }
Esempio n. 22
0
 /**
  * Returns a path between the source vertex <tt>s</tt> and vertex <tt>v</tt>, or <tt>null</tt> if
  * no such path.
  *
  * @param v the vertex
  * @return the sequence of vertices on a path between the source vertex <tt>s</tt> and vertex
  *     <tt>v</tt>, as an Iterable
  */
 public Iterable<Integer> pathTo(int v) {
   if (!hasPathTo(v)) return null;
   Stack<Integer> path = new Stack<Integer>();
   for (int x = v; x != s; x = edgeTo[x]) path.push(x);
   path.push(s);
   return path;
 }
Esempio n. 23
0
 /** main method for solver. solves a sudoku puzzle */
 public static void main(String[] args) {
   Stack<GameBoard> stack = new LinkedList<GameBoard>(); // intializes stack
   GameBoard board = new GameBoard(); // creates the game board
   stack.push(board);
   boolean solved = false;
   while (solved == false) {
     if (stack.isEmpty()) // if stack is empty the board is unsolvable
     System.out.println("board is unsolvable");
     GameBoard curr = stack.pop();
     if (curr.solved()) {
       System.out.println(curr);
       solved = true;
       return;
     }
     int[] mostConstrained =
         curr
             .mostConstrained(); // array containing the row and column of the most constrined spot
                                 // on the board
     for (int i = 1; i < 10; i++) // checks what numbers can be placed at the most constrained spot
     {
       if (curr.canPlace(mostConstrained[0], mostConstrained[1], i)) {
         GameBoard temp =
             new GameBoard(
                 curr); // calls the copy constructor and creates a copy of current game board
         temp.place(mostConstrained[0], mostConstrained[1], i);
         stack.push(temp);
       }
     }
   }
 }
Esempio n. 24
0
 public List<Interval> merge(List<Interval> intervals) {
   if (intervals == null) return null;
   Collections.sort(intervals, new IntervalComparator());
   Stack<Interval> stack = new Stack<Interval>();
   for (Interval i : intervals) {
     if (stack.isEmpty()) {
       stack.push(i);
     } else {
       Interval t = stack.peek();
       if (hasOverlap(t, i)) {
         Interval newInterval = new Interval(t.start, Math.max(t.end, i.end));
         stack.pop();
         stack.push(newInterval);
       } else {
         stack.push(i);
       }
     }
   }
   int length = stack.size() - 1;
   Interval[] intervalArray = new Interval[stack.size()];
   for (int i = length; i >= 0; i--) {
     intervalArray[i] = stack.pop();
   }
   return Arrays.asList(intervalArray);
 }
  public int largestRectangleArea(int[] height) {

    int area = 0, border;
    Stack<Node> heightStack = new Stack<Node>();
    heightStack.push(new Node(-1, -1));
    Node temNode;
    for (int i = 0; i < height.length; i++) {
      if (heightStack.peek().height < height[i]) {
        heightStack.push(new Node(height[i], i));
      } else {
        temNode = heightStack.peek();
        border = temNode.index;
        while (heightStack.peek().height > height[i]) {
          temNode = heightStack.pop();
          area = Math.max((border - heightStack.peek().index) * temNode.height, area);
        }
        area = Math.max((i - heightStack.peek().index) * height[i], area);
        heightStack.push(new Node(height[i], i));
      }
    }
    border = heightStack.peek().index;
    while (!heightStack.empty()) {
      Node tem = heightStack.pop();
      if (heightStack.empty()) return area;
      area = Math.max(area, tem.height * (border - heightStack.peek().index));
    }
    return area;
  }
  public int longestValidParentheses(String s) {
    Stack<int[]> stack = new Stack<int[]>();
    int result = 0;

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '(') {
        int[] a = {i, 0};
        stack.push(a);
      } else {
        if (stack.empty() || stack.peek()[1] == 1) {
          int[] a = {i, 1};
          stack.push(a);
        } else {
          stack.pop();
          int currentLen = 0;
          if (stack.empty()) {
            currentLen = i + 1;
          } else {
            currentLen = i - stack.peek()[0];
          }
          result = Math.max(result, currentLen);
        }
      }
    }

    return result;
  }
Esempio n. 27
0
  public static boolean pastTM_Al(Stack s) {
    byte[] topElmt = ((Entry) s.peek()).getPart();
    byte[] oldTopElmt = topElmt;

    if (BooleanMethod.endsWith_PastTMHuman_Al(topElmt)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "TM_Al");
      s.pop();
      s.push(new Entry(Constant.Al, Tag.ConditionalSuffix));
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.Al.length);
      s.push(new Entry(topElmt, -1, oldTopElmt));

      Tense.human(s);
      return true;
    }
    if (BooleanMethod.endsWith_PastTMHuman_Alum(topElmt)) {
      // clia.unl.unicode.utils.Utils.printOut(Analyser.print, x + "TM_Alum");
      s.pop();
      s.push(new Entry(Constant.um, Tag.Clitic));
      s.push(new Entry(Constant.Al, Tag.ConditionalSuffix));
      topElmt = ByteMeth.subArray(topElmt, 0, topElmt.length - Constant.Alum.length);
      s.push(new Entry(topElmt, -1, oldTopElmt));

      Tense.human(s);
      return true;
    }
    return false;
  }
 public boolean isValid(String s) {
   if (s == null || s.equals("()") || s.equals("{}") || s.equals("[]")) {
     return true;
   }
   char[] arr = s.toCharArray();
   Stack<Character> stack = new Stack<Character>();
   stack.push(arr[0]);
   for (int i = 1; i < s.length(); i++) {
     if ("({[".indexOf(arr[i] + "") != -1) {
       stack.push(arr[i]);
       continue;
     }
     if (stack.isEmpty()) {
       return false;
     }
     if (arr[i] == ')' && stack.peek() != '(') {
       return false;
     }
     if (arr[i] == '}' && stack.peek() != '{') {
       return false;
     }
     if (arr[i] == ']' && stack.peek() != '[') {
       return false;
     }
     stack.pop();
   }
   if (!stack.isEmpty()) {
     return false;
   }
   return true;
 }
  private void evaluateStack() {
    if (stack.isNull()) throw new IllegalArgumentException("stack");

    Stack thisStack = stack;
    int total = 0;

    while (thisStack != null) {
      String val = thisStack.pop();

      if (val.equals("+")) {
        String int1 = thisStack.pop();
        String int2 = thisStack.pop();

        total = Integer.parseInt(int1) + Integer.parseInt(int2);

        thisStack.push(Integer.toString(total));
      } else if (val.equals("s")) {
        String int1 = thisStack.pop();
        String int2 = thisStack.pop();

        thisStack.push(int1);
        thisStack.push(int2);
      }
    }
  }
Esempio n. 30
0
  public int maximalRectangle(char[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    int cLen = matrix[0].length; // column length
    int rLen = matrix.length; // row length
    // height array
    int[] h = new int[cLen + 1];
    h[cLen] = 0;
    int max = 0;

    for (int row = 0; row < rLen; row++) {
      Stack<Integer> s = new Stack<Integer>();
      for (int i = 0; i < cLen + 1; i++) {
        if (i < cLen)
          if (matrix[row][i] == '1') h[i] += 1;
          else h[i] = 0;

        if (s.isEmpty() || h[s.peek()] <= h[i]) s.push(i);
        else {
          while (!s.isEmpty() && h[i] < h[s.peek()]) {
            int top = s.pop();
            int area = h[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
            if (area > max) max = area;
          }
          s.push(i);
        }
      }
    }
    return max;
  }