Created
April 21, 2023 21:47
-
-
Save so77id/3d509178d39820c9260c4cc7d0540e95 to your computer and use it in GitHub Desktop.
Ejerciciso pre solemne 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class BalancedParentheses { | |
public static boolean isBalanced(String expression) { | |
Stack<Character> stack = new Stack<Character>(); | |
for (int i = 0; i < expression.length(); i++) { | |
char c = expression.charAt(i); | |
if (c == '(' || c == '{' || c == '[') { | |
stack.push(c); | |
} else if (c == ')' || c == '}' || c == ']') { | |
if (stack.isEmpty()) { | |
return false; | |
} | |
char last = stack.peek(); | |
if ((c == ')' && last == '(') || | |
(c == '}' && last == '{') || | |
(c == ']' && last == '[')) { | |
stack.pop(); | |
} else { | |
return false; | |
} | |
} | |
} | |
if (stack.isEmpty()) return true; | |
else return false; | |
return stack.isEmpty(); | |
} | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
System.out.print("Enter an expression: "); | |
String expression = scanner.nextLine(); | |
boolean balanced = isBalanced(expression); | |
if (balanced) { | |
System.out.println("The expression is balanced"); | |
} else { | |
System.out.println("The expression is not balanced"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class nextGreater { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int n = sc.nextInt(); | |
List<Integer> nums = new ArrayList<>(); | |
for (int i = 0; i < n; i++) { | |
nums.add(sc.nextInt()); | |
} | |
List<Integer> result = nextGreater(nums); | |
System.out.println(result); // Output: [5, 5, 9, -1, 8, -1] | |
} | |
public static List<Integer> nextGreater(List<Integer> nums) { | |
List<Integer> result = new ArrayList<>(nums.size()); | |
Stack<Integer> stack = new Stack<>(); | |
for (int i = nums.size() - 1; i >= 0; i--) { | |
while (!stack.isEmpty() && | |
stack.peek() <= nums.get(i)) { | |
stack.pop(); | |
} | |
result.add(stack.isEmpty() ? -1 : stack.peek()); | |
stack.push(nums.get(i)); | |
} | |
Collections.reverse(result); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment