Skip to content

Instantly share code, notes, and snippets.

@pellucide
Last active December 1, 2022 15:41
Show Gist options
  • Save pellucide/d87ede0462940625c2bd67e65b75ee34 to your computer and use it in GitHub Desktop.
Save pellucide/d87ede0462940625c2bd67e65b75ee34 to your computer and use it in GitHub Desktop.
/*
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(nested):
Input: s = "[(){}]"
Output: true
Example 5:
Input: s = "(({)})"
Output: false
*/
void main() {
test();
}
bool isValid(String input) {
final List<int> stack = [];
for (int i = 0; i < input.length; i++) {
int aChar = input.codeUnitAt(i);
if (aChar == '('.codeUnitAt(0) ||
aChar == '{'.codeUnitAt(0) ||
aChar == '['.codeUnitAt(0)) {
stack.add(aChar);
} else {
if (stack.isEmpty) {
return false;
}
int lastCh = stack.removeLast();
if (aChar == ')'.codeUnitAt(0) && lastCh != '('.codeUnitAt(0)) {
return false;
}
if (aChar == '}'.codeUnitAt(0) && lastCh != '{'.codeUnitAt(0)) {
return false;
}
if (aChar == ']'.codeUnitAt(0) && lastCh != '['.codeUnitAt(0)) {
return false;
}
}
}
return stack.isEmpty;
}
void test1(String input, bool expected) {
bool actual = isValid(input);
String valid = (expected == actual) ? "\u2713" : " x ";
print("expected=$expected, actual=$actual $valid");
}
void test() {
test1("[]", true);
test1("[{}]", true);
test1("[{}]({})", true);
test1("[()]{}", true);
test1("[{(})]", false);
test1("[()]}", false);
test1("{[()]", false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment