Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions dart/valid_parentheses.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if open brackets are closed by the same type of brackets and in the correct order.
*/

class Solution {
bool isValid(String s) {
final Map<String, String> pairs = {
')': '(',
'}': '{',
']': '[',
};
final List<String> stack = [];

for (int i = 0; i < s.length; i++) {
final String char = s[i];

if (pairs.containsValue(char)) {
stack.add(char);
} else if (stack.isEmpty || stack.removeLast() != pairs[char]) {
return false;
}
}

return stack.isEmpty;
}
}