-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparen.java
More file actions
71 lines (54 loc) · 1.92 KB
/
paren.java
File metadata and controls
71 lines (54 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.*;
class paren {
public static boolean isValid(String s) {
if (s == null || s.length() == 0) return false;
Stack <Character> stack = new Stack<>();
for (char b : s.toCharArray()) {
if (b == '(' || b == '{' || b == '[' ) {
stack.push(b);
} else if (!stack.isEmpty() && b == ')' && stack.peek() == '(') {
stack.pop();
}
else if (!stack.isEmpty() && b == '}' && stack.peek() == '{') {
stack.pop();
}
else if (!stack.isEmpty() && b == ']' && stack.peek() == '[') {
stack.pop();
}
else return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
String s1 = "()";
System.out.println(isValid(s1));
System.out.println();
String s2 = "([{])}";
System.out.println(isValid(s2));
System.out.println();
}
}
/*
https://leetcode.com/problems/valid-parentheses/
for each char:
if it is an opening paren, add to stack
if it is closing,
return False if does not match opening
else pop off the last char in stack
at end, stack must be empty
* Valid Parentheses Checker
Problem Statement:
You are given a string containing just the characters '(', ')', '{', '}', '[' and ']'. Write a function that determines if the input string has valid parentheses, meaning:
Every opening bracket has a corresponding and correctly placed closing bracket.
The brackets must be nested correctly (e.g., "(]" is invalid).
Requirements:
The function should return true if the string is valid, otherwise return false.
The function should run in O(n) time complexity and use O(n) space for the stack.
Example Cases:
Input: "()[]{}"
Output: true
Input: "([)]"
Output: false
Input: "{[]}"
Output: true
*/