November 15, 2020
Hello fellow devs π! Itβs a brand-new day and itβs time to solve another problem from LeetCode.
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
s.length
β€ 104s
consists of parentheses only '()[]{}'
.Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
In this question, we need to deal with only 6 symbols β (
, )
, {
, }
, [
, ]
. We will be given a string containing only these symbols. A string is valid if all the symbols are present in pairs and left parenthesis comes before the corresponding right.
This is a simple question π. We will traverse the string s
from left to right and see if left and right parentheses are matching with their corresponding counterpart.
Last In First Out (LIFO)
property.top
of the stack. If it is the correct corresponding open/left parenthesis, we will move further, else we will return false.We are traversing the string once, hence the time complexity will be O(n).
We are using Stack to store characters of the string, hence the space complexity will be O(n).
public class ValidParentheses {
public boolean isValid(String s) {
// Stack to store left symbols
Stack<Character> leftSymbols = new Stack<>();
// Loop for each character of the string
for (char c : s.toCharArray()) {
// If left symbol is encountered
if (c == '(' || c == '{' || c == '[') {
leftSymbols.push(c);
}
// If right symbol is encountered
else if (c == ')' && !leftSymbols.isEmpty() && leftSymbols.peek() == '(') {
leftSymbols.pop();
} else if (c == '}' && !leftSymbols.isEmpty() && leftSymbols.peek() == '{') {
leftSymbols.pop();
} else if (c == ']' && !leftSymbols.isEmpty() && leftSymbols.peek() == '[') {
leftSymbols.pop();
}
// If none of the valid symbols is encountered
else {
return false;
}
}
return leftSymbols.isEmpty();
}
}
def isValid(s: str) -> bool:
# Stack for left symbols
leftSymbols = []
# Loop for each character of the string
for c in s:
# If left symbol is encountered
if c in ['(', '{', '[']:
leftSymbols.append(c)
# If right symbol is encountered
elif c == ')' and len(leftSymbols) != 0 and leftSymbols[-1] == '(':
leftSymbols.pop()
elif c == '}' and len(leftSymbols) != 0 and leftSymbols[-1] == '{':
leftSymbols.pop()
elif c == ']' and len(leftSymbols) != 0 and leftSymbols[-1] == '[':
leftSymbols.pop()
# If none of the valid symbols is encountered
else:
return False
return leftSymbols == []
var isValid = function (s) {
// Stack to store left symbols
const leftSymbols = [];
// Loop for each character of the string
for (let i = 0; i < s.length; i++) {
// If left symbol is encountered
if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
leftSymbols.push(s[i]);
}
// If right symbol is encountered
else if (s[i] === ')' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '(') {
leftSymbols.pop();
} else if (s[i] === '}' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '{') {
leftSymbols.pop();
} else if (s[i] === ']' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '[') {
leftSymbols.pop();
}
// If none of the valid symbols is encountered
else {
return false;
}
}
return leftSymbols.length === 0;
};
fun isValid(s: String): Boolean {
// Stack to store left symbols
val leftSymbols = Stack<Char>()
// Loop for each character of the string
for (c in s.toCharArray()) {
// If left symbol is encountered
if (c == '(' || c == '{' || c == '[') {
leftSymbols.push(c)
}
// If right symbol is encountered
else if (c == ')' && !leftSymbols.isEmpty() && leftSymbols.peek() == '(') {
leftSymbols.pop()
} else if (c == '}' && !leftSymbols.isEmpty() && leftSymbols.peek() == '{') {
leftSymbols.pop()
} else if (c == ']' && !leftSymbols.isEmpty() && leftSymbols.peek() == '[') {
leftSymbols.pop()
}
// If none of the valid symbols is encountered
else {
return false
}
}
return leftSymbols.isEmpty()
}
Congratulations π! We have solved the problem using two pointer technique which is very handy in solving a variety of linked list problems.
I hope you enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn, feel free to fork πͺ and star β it.
Till next timeβ¦ Happy coding π and Namaste π!