Skip to content

Commit b181bb0

Browse files
Update validParentheses.java
1 parent 8d92406 commit b181bb0

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

Topic/Solution/validParentheses.java

+49-1
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,64 @@
1+
/*
2+
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
3+
4+
An input string is valid if:
5+
6+
Open brackets must be closed by the same type of brackets.
7+
Open brackets must be closed in the correct order.
8+
9+
10+
Example 1:
11+
12+
Input: s = "()"
13+
Output: true
14+
Example 2:
15+
16+
Input: s = "()[]{}"
17+
Output: true
18+
Example 3:
19+
20+
Input: s = "(]"
21+
Output: false
22+
Example 4:
23+
24+
Input: s = "([)]"
25+
Output: false
26+
Example 5:
27+
28+
Input: s = "{[]}"
29+
Output: true
30+
31+
32+
Constraints:
33+
34+
1 <= s.length <= 104
35+
s consists of parentheses only '()[]{}'.
36+
37+
*/
38+
39+
40+
// funtional code
41+
142
class Solution {
243
public boolean isValid(String s) {
344
if (s.length() % 2 != 0) return false;
45+
46+
// create a stack to store parentheses.
447
Stack<Character> stack = new Stack<>();
548
for (int i = 0; i < s.length(); i++) {
649
char c = s.charAt(i);
50+
// push opening parentheses.
751
if (c == '(') {
852
stack.push(')');
953
} else if (c == '[') {
1054
stack.push(']');
1155
} else if (c == '{') {
1256
stack.push('}');
13-
} else if (stack.isEmpty() || stack.pop() != c) return false;
57+
}
58+
// check for coressponding closing parentheses if it is not there then return false.
59+
else if (stack.isEmpty() || stack.pop() != c) return false;
1460
}
61+
62+
// if the stack is empty that means parentheses are valid.
1563
return stack.isEmpty();
1664
}

0 commit comments

Comments
 (0)