In the Leetcode Valid Parentheses problem solution in Java programming Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Leetcode Valid Parentheses problem solution in Java programming
import java.util.*;
class Solution {
Stack<Character> stack = new Stack<Character>();
Map<Character, Character> map = new HashMap<Character, Character>();
public Solution() {
map.put('[', ']');
map.put('{', '}');
map.put('(', ')');
}
public boolean isValid(String s) {
if (s.length() < 2) {
return false;
}
for (int i = 0; i < s.length(); i++) {
Character currentChar = s.charAt(i);
if (map.get(currentChar) != null) {
stack.push(map.get(currentChar));
} else if (stack.size() == 0) {
return false;
} else if (currentChar == stack.peek()) {
stack.pop();
} else {
return false;
}
}
if (stack.size() > 0) {
return false;
}
return true;
}
}
Also read,
- Leetcode Valid Parentheses problem solution in C++
- Leetcode Valid Parentheses problem solution in C
- Leetcode Valid Parentheses problem solution in Python
- Leetcode Valid Parentheses problem solution in C#