mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-27 06:23:08 +08:00
@ -28,16 +28,13 @@ class BalancedBrackets {
|
||||
*/
|
||||
public static boolean isPaired(char leftBracket, char rightBracket) {
|
||||
char[][] pairedBrackets = {
|
||||
{ '(', ')' },
|
||||
{ '[', ']' },
|
||||
{ '{', '}' },
|
||||
{ '<', '>' },
|
||||
{'(', ')'},
|
||||
{'[', ']'},
|
||||
{'{', '}'},
|
||||
{'<', '>'},
|
||||
};
|
||||
for (char[] pairedBracket : pairedBrackets) {
|
||||
if (
|
||||
pairedBracket[0] == leftBracket &&
|
||||
pairedBracket[1] == rightBracket
|
||||
) {
|
||||
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -58,24 +55,21 @@ class BalancedBrackets {
|
||||
Stack<Character> bracketsStack = new Stack<>();
|
||||
for (char bracket : brackets.toCharArray()) {
|
||||
switch (bracket) {
|
||||
case '(':
|
||||
case '[':
|
||||
case '{':
|
||||
bracketsStack.push(bracket);
|
||||
break;
|
||||
case ')':
|
||||
case ']':
|
||||
case '}':
|
||||
if (
|
||||
bracketsStack.isEmpty() ||
|
||||
!isPaired(bracketsStack.pop(), bracket)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
/* other character is invalid */
|
||||
case '(':
|
||||
case '[':
|
||||
case '{':
|
||||
bracketsStack.push(bracket);
|
||||
break;
|
||||
case ')':
|
||||
case ']':
|
||||
case '}':
|
||||
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
/* other character is invalid */
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return bracketsStack.isEmpty();
|
||||
|
@ -1,8 +1,12 @@
|
||||
/** Author : Siddhant Swarup Mallick
|
||||
/**
|
||||
* Author : Siddhant Swarup Mallick
|
||||
* Github : https://github.com/siddhant2002
|
||||
*/
|
||||
|
||||
/** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */
|
||||
/**
|
||||
* Program description - Given an integer array. The task is to find the maximum of the minimum of
|
||||
* the array
|
||||
*/
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.*;
|
||||
|
@ -24,12 +24,7 @@ public class DecimalToAnyUsingStack {
|
||||
private static String convert(int number, int radix) {
|
||||
if (radix < 2 || radix > 16) {
|
||||
throw new ArithmeticException(
|
||||
String.format(
|
||||
"Invalid input -> number:%d,radius:%d",
|
||||
number,
|
||||
radix
|
||||
)
|
||||
);
|
||||
String.format("Invalid input -> number:%d,radius:%d", number, radix));
|
||||
}
|
||||
char[] tables = {
|
||||
'0',
|
||||
|
@ -1,7 +1,8 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
// 1. You are given a string exp representing an expression.
|
||||
// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other.
|
||||
// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each
|
||||
// other.
|
||||
// 3. But, some of the pair of brackets maybe extra/needless.
|
||||
// 4. You are required to print true if you detect extra brackets and false otherwise.
|
||||
// e.g.'
|
||||
|
@ -10,8 +10,7 @@ public class InfixToPostfix {
|
||||
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
|
||||
}
|
||||
|
||||
public static String infix2PostFix(String infixExpression)
|
||||
throws Exception {
|
||||
public static String infix2PostFix(String infixExpression) throws Exception {
|
||||
if (!BalancedBrackets.isBalanced(infixExpression)) {
|
||||
throw new Exception("invalid expression");
|
||||
}
|
||||
@ -28,10 +27,7 @@ public class InfixToPostfix {
|
||||
}
|
||||
stack.pop();
|
||||
} else {
|
||||
while (
|
||||
!stack.isEmpty() &&
|
||||
precedence(element) <= precedence(stack.peek())
|
||||
) {
|
||||
while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) {
|
||||
output.append(stack.pop());
|
||||
}
|
||||
stack.push(element);
|
||||
@ -45,16 +41,16 @@ public class InfixToPostfix {
|
||||
|
||||
private static int precedence(char operator) {
|
||||
switch (operator) {
|
||||
case '+':
|
||||
case '-':
|
||||
return 0;
|
||||
case '*':
|
||||
case '/':
|
||||
return 1;
|
||||
case '^':
|
||||
return 2;
|
||||
default:
|
||||
return -1;
|
||||
case '+':
|
||||
case '-':
|
||||
return 0;
|
||||
case '*':
|
||||
case '/':
|
||||
return 1;
|
||||
case '^':
|
||||
return 2;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ public class LargestRectangle {
|
||||
maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0]));
|
||||
start = tmp[0];
|
||||
}
|
||||
st.push(new int[] { start, heights[i] });
|
||||
st.push(new int[] {start, heights[i]});
|
||||
}
|
||||
while (!st.isEmpty()) {
|
||||
int[] tmp = st.pop();
|
||||
@ -29,8 +29,7 @@ public class LargestRectangle {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 })
|
||||
.equals("10");
|
||||
assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4");
|
||||
assert largestRectanglehistogram(new int[] {2, 1, 5, 6, 2, 3}).equals("10");
|
||||
assert largestRectanglehistogram(new int[] {2, 4}).equals("4");
|
||||
}
|
||||
}
|
||||
|
@ -97,8 +97,8 @@ public class MaximumMinimumWindow {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
|
||||
int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
|
||||
int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30};
|
||||
int[] target = new int[] {70, 30, 20, 10, 10, 10, 10};
|
||||
int[] res = calculateMaxOfMin(arr, arr.length);
|
||||
assert Arrays.equals(target, res);
|
||||
}
|
||||
|
@ -37,7 +37,8 @@ import java.util.Stack;
|
||||
popped elements.
|
||||
d. Finally, push the next in the stack.
|
||||
|
||||
3. If elements are left in stack after completing while loop then their Next Grater element is -1.
|
||||
3. If elements are left in stack after completing while loop then their Next Grater element is
|
||||
-1.
|
||||
*/
|
||||
|
||||
public class NextGraterElement {
|
||||
@ -61,7 +62,7 @@ public class NextGraterElement {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] input = { 2, 7, 3, 5, 4, 6, 8 };
|
||||
int[] input = {2, 7, 3, 5, 4, 6, 8};
|
||||
int[] result = findNextGreaterElements(input);
|
||||
System.out.println(Arrays.toString(result));
|
||||
}
|
||||
|
@ -4,10 +4,10 @@ import java.util.Arrays;
|
||||
import java.util.Stack;
|
||||
|
||||
/*
|
||||
Given an array "input" you need to print the first smaller element for each element to the left side of an array.
|
||||
For a given element x of an array, the Next Smaller element of that element is the
|
||||
first smaller element to the left side of it. If no such element is present print -1.
|
||||
|
||||
Given an array "input" you need to print the first smaller element for each element to the left
|
||||
side of an array. For a given element x of an array, the Next Smaller element of that element is
|
||||
the first smaller element to the left side of it. If no such element is present print -1.
|
||||
|
||||
Example
|
||||
input = { 2, 7, 3, 5, 4, 6, 8 };
|
||||
At i = 0
|
||||
@ -24,17 +24,17 @@ import java.util.Stack;
|
||||
Next smaller element between (0 , 4) is 4
|
||||
At i = 6
|
||||
Next smaller element between (0 , 5) is 6
|
||||
|
||||
|
||||
result : [-1, 2, 2, 3, 3, 4, 6]
|
||||
|
||||
|
||||
1) Create a new empty stack st
|
||||
|
||||
|
||||
2) Iterate over array "input" , where "i" goes from 0 to input.length -1.
|
||||
a) We are looking for value just smaller than `input[i]`. So keep popping from "stack"
|
||||
a) We are looking for value just smaller than `input[i]`. So keep popping from "stack"
|
||||
till elements in "stack.peek() >= input[i]" or stack becomes empty.
|
||||
b) If the stack is non-empty, then the top element is our previous element. Else the previous element does not exist.
|
||||
c) push input[i] in stack.
|
||||
3) If elements are left then their answer is -1
|
||||
b) If the stack is non-empty, then the top element is our previous element. Else the
|
||||
previous element does not exist. c) push input[i] in stack. 3) If elements are left then their
|
||||
answer is -1
|
||||
*/
|
||||
|
||||
public class NextSmallerElement {
|
||||
@ -61,7 +61,7 @@ public class NextSmallerElement {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] input = { 2, 7, 3, 5, 4, 6, 8 };
|
||||
int[] input = {2, 7, 3, 5, 4, 6, 8};
|
||||
int[] result = findNextSmallerElements(input);
|
||||
System.out.println(Arrays.toString(result));
|
||||
}
|
||||
|
@ -50,7 +50,8 @@ public class NodeStack<Item> {
|
||||
/**
|
||||
* Constructors for the NodeStack.
|
||||
*/
|
||||
public NodeStack() {}
|
||||
public NodeStack() {
|
||||
}
|
||||
|
||||
private NodeStack(Item item) {
|
||||
this.data = item;
|
||||
|
@ -20,12 +20,12 @@ public class PostfixToInfix {
|
||||
|
||||
public static boolean isOperator(char token) {
|
||||
switch (token) {
|
||||
case '+':
|
||||
case '-':
|
||||
case '/':
|
||||
case '*':
|
||||
case '^':
|
||||
return true;
|
||||
case '+':
|
||||
case '-':
|
||||
case '/':
|
||||
case '*':
|
||||
case '^':
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
@ -42,7 +42,8 @@ public class PostfixToInfix {
|
||||
int operandCount = 0;
|
||||
int operatorCount = 0;
|
||||
|
||||
/* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */
|
||||
/* Traverse the postfix string to check if --> Number of operands = Number of operators + 1
|
||||
*/
|
||||
for (int i = 0; i < postfix.length(); i++) {
|
||||
char token = postfix.charAt(i);
|
||||
|
||||
@ -59,8 +60,8 @@ public class PostfixToInfix {
|
||||
|
||||
/* Operand count is set to 2 because:-
|
||||
*
|
||||
* 1) the previous set of operands & operators combined have become a single valid expression,
|
||||
* which could be considered/assigned as a single operand.
|
||||
* 1) the previous set of operands & operators combined have become a single valid
|
||||
* expression, which could be considered/assigned as a single operand.
|
||||
*
|
||||
* 2) the operand in the current iteration.
|
||||
*/
|
||||
@ -123,7 +124,6 @@ public class PostfixToInfix {
|
||||
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
|
||||
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
|
||||
assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))");
|
||||
assert getPostfixToInfix("AB+CD^/E*FGH+-^")
|
||||
.equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
|
||||
assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
|
||||
}
|
||||
}
|
||||
|
@ -12,9 +12,7 @@ public class ReverseStack {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println(
|
||||
"Enter the number of elements you wish to insert in the stack"
|
||||
);
|
||||
System.out.println("Enter the number of elements you wish to insert in the stack");
|
||||
int n = sc.nextInt();
|
||||
int i;
|
||||
Stack<Integer> stack = new Stack<Integer>();
|
||||
@ -36,28 +34,29 @@ public class ReverseStack {
|
||||
return;
|
||||
}
|
||||
|
||||
//Store the topmost element
|
||||
// Store the topmost element
|
||||
int element = stack.peek();
|
||||
//Remove the topmost element
|
||||
// Remove the topmost element
|
||||
stack.pop();
|
||||
|
||||
//Reverse the stack for the leftover elements
|
||||
// Reverse the stack for the leftover elements
|
||||
reverseStack(stack);
|
||||
|
||||
//Insert the topmost element to the bottom of the stack
|
||||
// Insert the topmost element to the bottom of the stack
|
||||
insertAtBottom(stack, element);
|
||||
}
|
||||
|
||||
private static void insertAtBottom(Stack<Integer> stack, int element) {
|
||||
if (stack.isEmpty()) {
|
||||
//When stack is empty, insert the element so it will be present at the bottom of the stack
|
||||
// When stack is empty, insert the element so it will be present at the bottom of the
|
||||
// stack
|
||||
stack.push(element);
|
||||
return;
|
||||
}
|
||||
|
||||
int ele = stack.peek();
|
||||
/*Keep popping elements till stack becomes empty. Push the elements once the topmost element has
|
||||
moved to the bottom of the stack.
|
||||
/*Keep popping elements till stack becomes empty. Push the elements once the topmost element
|
||||
has moved to the bottom of the stack.
|
||||
*/
|
||||
stack.pop();
|
||||
insertAtBottom(stack, element);
|
||||
|
@ -23,9 +23,7 @@ class StackOfLinkedList {
|
||||
assert stack.pop() == 5;
|
||||
assert stack.pop() == 4;
|
||||
|
||||
System.out.println(
|
||||
"Top element of stack currently is: " + stack.peek()
|
||||
);
|
||||
System.out.println("Top element of stack currently is: " + stack.peek());
|
||||
}
|
||||
}
|
||||
|
||||
@ -120,9 +118,7 @@ class LinkedListStack {
|
||||
builder.append(cur.data).append("->");
|
||||
cur = cur.next;
|
||||
}
|
||||
return builder
|
||||
.replace(builder.length() - 2, builder.length(), "")
|
||||
.toString();
|
||||
return builder.replace(builder.length() - 2, builder.length(), "").toString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user