My solution to a “Daily Coding Problem” that I received in my mail today.
You’re given a string consisting solely of
(
, )
, and *
. *
can represent either a (
, )
, or an empty string. Determine whether the parentheses are balanced.
For example,
(()*
and (*)
are balanced. )*(
is not balanced.
Here’s my solution in Typescript,
oneFortyTwo(str: string): boolean {
if(str == undefined || str == null) {
return false;
}
//not sure if this is right?
if(str.length == 1){
return false;
}
let balanced: boolean = false;
let parenStack = new Stack<string>();
for(let i=0; i < str.length; i++) {
let char = str.charAt(i);
let topChar = parenStack.peek();
if(topChar == null) {
parenStack.push(char);
} else {
if(topChar == "*") {
parenStack.pop();
} else if((char == "(" || char == "*") && (topChar == ")" || topChar == "*")) {
parenStack.pop();
} else if((char == ")" || char == "*") && (topChar == "(" || topChar == "*")) {
parenStack.pop();
} else {
parenStack.push(char)
}
}
}
return parenStack.isEmpty() ? true: false;
}
I know, it wasn’t exactly super essential but I wrote the code for a custom Stack class anyway.
class Stack<T> {
data:Array<T> = [];
constructor(){
this.data = new Array<T>();
}
isEmpty(): boolean {
return (this.data.length == 0);
}
getSize() {
return this.data.length;
}
push(elem:T) {
this.data.push(elem);
}
pop() {
return this.data.pop();
}
peek() {
if (this.data.length > 0) {
return this.data[(this.data.length - 1)];
} else {
return null;
}
}
}
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
No comments:
Post a Comment