Created
September 14, 2023 14:37
-
-
Save singlesoup/66355ed74267a299d6775c7babc85a97 to your computer and use it in GitHub Desktop.
Balance the Parentheses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Challenge 2: Balance the Parentheses | |
void main() { | |
// String ip = 'h((e))llo(world)()'; | |
String ip = '(hello world'; | |
List l = ip.split(''); | |
Stack stack = Stack(inputList: l); | |
int listLen = l.length; | |
int openingB = 0; | |
int closingB = 0; | |
for (int i = listLen - 1; i >= 0; i--) { | |
// print(l[i]); | |
if (l[i] == ')') { | |
openingB += 1; | |
} else if (l[i] == '(') { | |
closingB += 1; | |
} | |
stack.pop(); | |
} | |
print("openB:$openingB - closeB:$closingB"); | |
if (closingB == openingB) { | |
print('balanced'); | |
} else { | |
print('not Balanced'); | |
} | |
} | |
class Stack { | |
final List inputList; | |
Stack({ | |
required this.inputList, | |
}); | |
get peek => inputList.last; | |
void push(dynamic element) => inputList.add(element); | |
void pop() => inputList.removeLast(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment