-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplaceParenthesis
More file actions
58 lines (42 loc) · 1.33 KB
/
replaceParenthesis
File metadata and controls
58 lines (42 loc) · 1.33 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# You are given input string containing alphabetical chaterters and parenthesis. Convert the input string into following format.
# "()" => "00"
# ")(" => "-11"
# "((ab)" => "10ab0"
# "(a(b)c)" => "0a0b0c0"
# "()a((((" => "00a1111"
# "(a))))b(((" => "0a0-1-1-1b111"
# (a(b)c)
# Stack: [0a0b0c0]
# Replace both opening and closing braces with 0 if parenthesis are balanced
# If parenthesis are not balance, replace '(' -> 1 and ')' -> -1.
let str="((ab)"
function replaceParenthesis(str){
let stack=[]
for(let i=0; i<str.length; i++){
let temp='',top// reinitialize
if(str[i]==')'){
temp=')'
while(top!=='(' && stack.length>0){
top=stack.pop()
temp=top+temp//opposite order append
}
// just for the balanced replacement
if(temp.charAt(temp.length-1)==')' && temp.charAt(0)=='('){
temp=temp.replace('(','0')
temp=temp.replace(')','0')
}
for(let j=0; j<temp.length; j++){
stack.push(temp[j])//push all the pop element into the stack
}
}
else stack.push(str[i])
}
//now assign imbalance mapping, replace '(' -> 1 and ')' -> -1
for(let k=0;k<stack.length;k++){
if(stack[k]=='(') stack[k]='1'
else if(stack[k]==')')stack[k]='-1'
}
stack=stack.join('')
console.log('Finalstack',stack)
}
replaceParenthesis(str)