Problem
DailyCodingProblem
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string ”([])”, you should return true.
Given the string ”([)]” or ”((()”, you should return false.
LeetCode
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.
Example 1: Input: s = ”()” Output: true
Example 2: Input: s = ”()[]{}” Output: true
Example 3: Input: s = ”(]” Output: false
Example 4: Input: s = ”([])” Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
HackerRank
A bracket is considered to be any one of the following characters: (
, )
, {
, }
, [
, or ]
.
Two brackets are considered to be a matched pair if the an opening bracket (i.e., (
, [
, or {
) occurs to the left of a closing bracket (i.e., )
, ]
, or }
) of the exact same type. There are three types of matched pairs of brackets: []
, {}
, and ()
.
A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])}
is not balanced because the contents in between {
and }
are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (
, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]
.
By this logic, we say a sequence of brackets is balanced if the following conditions are met:
- It contains no unmatched brackets.
- The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.
Given strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES
. Otherwise, return NO
.
Function Description Complete the function isBalanced in the editor below. isBalanced has the following parameter(s):
- string s: a string of brackets Returns
- string: either
YES
orNO
Input Format
The first line contains a single integer , the number of strings.
Each of the next lines contains a single string , a sequence of brackets.
Constraints
- , where is the length of the sequence.
- All chracters in the sequences ∈ { {, }, (, ), [, ] }.
Output Format
For each string, return YES
or NO
.
Sample Input STDIN Function ----- -------- 3 n = 3 {[()]} first s = ’{[()]}’ {[(])} second s = ’{[(])}’ {{(())}} third s =’{{(())}}’
Sample Output
YES
NO
YES
Explanation
- The string
{[()]}
meets both criteria for being a balanced string. - The string
{[(])}
is not balanced because the brackets enclosed by the matched pair{
and}
are not balanced:[(])
. - The string
{{[[(())]]}}
meets both criteria for being a balanced string.
Solution
Stack - O(n) time - O(n) space
Technically O(s)
time and O(s)
space because s
is the variable that refers to string length, while n
in the problem refers to the number of strings
string isBalanced(string s) {
stack<char> brackets;
for (char c : s) {
if (c == '{' || c == '(' || c == '[') {
brackets.push(c);
continue;
}
if (brackets.empty()) return "NO";
char last = brackets.top();
if ((last == '{' && c == '}')
|| (last == '(' && c == ')')
|| (last == '[' && c == ']')) {
brackets.pop();
} else return "NO";
}
return brackets.empty() ? "YES" : "NO";
}
Could also use a dictionary for matching for better readability
string isBalanced(string s) {
stack<char> brackets;
unordered_map<char, char> match = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : s) {
if (c == '{' || c == '(' || c == '[') {
brackets.push(c);
}
else if (brackets.empty() || match[c] != brackets.top()) {
return "NO";
} else brackets.pop();
}
return brackets.empty() ? "YES" : "NO";
}
Given the only characters in the input are valid we can make it even shorter and more readable
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> matching = {{']','['}, {')','('}, {'}','{'}};
stack<char> symbols;
for (char c : s) {
if (!symbols.empty() && matching[c] == symbols.top()) {
symbols.pop();
}
else symbols.push(c);
}
return symbols.empty() ? true : false;
}
};