Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
An input string is valid if:
1 <= s.length <= 10000s consists of parentheses only ()[]{}.Use a stack of characters.
When you encounter an opening bracket, push it to the top of the stack.
When you encounter a closing bracket, check if the top of the stack was the opening for it. If yes, pop it from the stack. Otherwise, return false.
No developer has claimed the Javascript throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned./**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
const closeToOpen = new Map([
[')', '('],
['}', '{'],
[']', '['],
])
const stack = []
for (const char of s) {
if (!closeToOpen.has(char)) {
// is open bracket
stack.push(char)
continue
}
// is close bracket
if (stack.length === 0) {
return false
}
// stack top value doesn't match the expected value
if (stack.pop() != closeToOpen.get(char)) {
return false
}
}
return stack.length === 0
};
No developer has claimed the Python throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.# Solution 1, a bit complex.
class Solution:
def isValid(self, s: str) -> bool:
# Map closing brackets to their opening brackets
close_to_open = {
')': '(',
'}': '{',
']': '[',
}
stack = []
for char in s:
if char not in close_to_open:
# is open bracket
stack.append(char)
continue
# is close bracket
if not stack:
return False
# stack top value doesn't match the expected value
if stack.pop() != close_to_open[char]:
return False
return not stack
# Solution 2, more concise.
class Solution:
def isValid(self, s: str) -> bool:
left_to_right = { '(': ')', '{': '}', '[': ']' }
st = []
for c in s:
if st and st[-1] in left_to_right and left_to_right[st[-1]] == c:
st.pop()
else:
st.append(c)
return not st
No developer has claimed the Java throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.class Solution {
public boolean isValid(String s) {
// Map closing brackets to their opening brackets
var closeToOpen = new HashMap<Character, Character>();
closeToOpen.put(')', '(');
closeToOpen.put('}', '{');
closeToOpen.put(']', '[');
var stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (!closeToOpen.containsKey(c)) {
// is open bracket
stack.push(c);
continue;
}
// is close bracket
if (stack.isEmpty()) {
return false;
}
// stack top value doesn't match the expected value
if (stack.pop() != closeToOpen.get(c)) {
return false;
}
}
return stack.isEmpty();
}
}
No developer has claimed the C++ throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.class Solution {
public:
bool isValid(string s) {
// Map closing brackets to their opening brackets
unordered_map<char, char> closeToOpen = {
{')', '('},
{'}', '{'},
{']', '['}
};
stack<char> st;
for (char c : s) {
if (closeToOpen.find(c) == closeToOpen.end()) {
// is open bracket
st.push(c);
continue;
}
// is close bracket
if (st.empty()) {
return false;
}
// stack top value doesn't match the expected value
if (st.top() != closeToOpen[c]) {
return false;
}
st.pop();
}
return st.empty();
}
};
No developer has claimed the C# throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.public class Solution
{
public bool IsValid(string s)
{
// Map closing brackets to their opening brackets
var closeToOpen = new Dictionary<char, char>()
{
{')', '('},
{'}', '{'},
{']', '['}
};
var stack = new Stack<char>();
foreach (char c in s) {
if (!closeToOpen.ContainsKey(c))
{
// is open bracket
stack.Push(c);
continue;
}
// is close bracket
if (stack.Count == 0)
{
return false;
}
// stack top value doesn't match the expected value
if (stack.Pop() != closeToOpen[c])
{
return false;
}
}
return stack.Count == 0;
}
}
No developer has claimed the Go throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.func isValid(s string) bool {
// Map closing brackets to their opening brackets
closeToOpen := map[rune]rune{
')': '(',
'}': '{',
']': '[',
}
stack := []rune{}
for _, char := range s {
if _, isClose := closeToOpen[char]; !isClose {
// is open bracket
stack = append(stack, char)
continue
}
// is close bracket
if len(stack) == 0 {
return false
}
lastChar := stack[len(stack) - 1]
// stack top value doesn't match the expected value
if lastChar != closeToOpen[char] {
return false
}
stack = stack[:len(stack) - 1] // pop operation
}
return len(stack) == 0
}
No developer has claimed the Ruby throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
previous character and the current character. There are two situations to consider:
current character is a left bracket, there is no need to match it and it can be saved directly.current character is a right bracket, and the previous character and the current character are paired, both characters can disappear; otherwise, if the pairing fails, false is returned directly.previous character and the current character is suitable for implementation with a stack.Map.true is returned; otherwise, false is returned.# @param {String} s
# @return {Boolean}
def is_valid(s)
# Map closing brackets to their opening brackets
close_to_open = {
')' => '(',
'}' => '{',
']' => '['
}
stack = []
s.each_char do |char|
if !close_to_open.key?(char)
# is open bracket
stack.push(char)
next
end
# is close bracket
if stack.empty?
return false
end
# stack top value doesn't match the expected value
if stack.pop != close_to_open[char]
return false
end
end
stack.empty?
end
No developer has claimed the Rust throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Swift throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Kotlin throne for LeetCode #20 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.