-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20 Valid Parentheses.dart
35 lines (31 loc) · 1.12 KB
/
20 Valid Parentheses.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
bool isValid(String s) {
//Map to check if checkerList has its opener.
Map<String, String> relations = {")": "(", "}": "{", "]": "["};
//CheckerList to store the openings.
List<String> checker = [];
//Traverse through all the characters from given string.
for (String e in s.split('')) {
//If current element is closer
if (relations.containsKey(e)) {
//If checkerList has elements in it and current element is closer for last element at checkerlist.
if (checker.isNotEmpty && checker.last == relations[e]) {
//Remove the last element, since it is correctly closed.
checker.removeLast();
} else {
//If current element is not correct closer, string is invalid.
return false;
}
} else {
//Since current element is opener add it to checkerList.
checker.add(e);
}
}
//After traversing is done, if there are still elements in checkerList, it is invalid. Else it is valid.
return checker.isEmpty;
}
}
void main() {
Solution sol = Solution();
print(sol.isValid("((]))"));
}