-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithms.html
54 lines (44 loc) · 1.15 KB
/
algorithms.html
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
<!DOCTYPE html>
<html>
<body>
<script>
function reverseString(s) {
return s.split("").reverse().map(c => {
if (c === '(') {
return ')';
} else if (c === ')') {
return '(';
}
return c;
}).join("");
}
function readAndReverseInsideParens(s, cursor) {
var accum = "";
while (cursor<s.length) {
var c = s[cursor];
// shift cursor right
cursor = cursor + 1;
// if the opening parens, call the recursive function
if (c == "(") {
var subStr;
[subStr, cursor] = readAndReverseInsideParens(s, cursor);
accum = accum + '(' + reverseString(subStr) + ')';
} else if (c==")") {
break;
} else {
accum = accum + c;
}
}
return [accum, cursor];
}
function reverseInParens(text){
var [reversed, cursor] = readAndReverseInsideParens(text, 0);
return reversed;
}
console.log(reverseInParens("h(el)lo"), "h(le)lo");
console.log(reverseInParens("a ((d e) c b)"), "a (b c (d e))");
console.log(reverseInParens("one (two (three) four)"), "one (ruof (three) owt)");
console.log(reverseInParens("one (ruof ((rht)ee) owt)"), "one (two ((thr)ee) four)");
</script>
</body>
</html>