-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-inner-string.js
More file actions
69 lines (60 loc) · 2.21 KB
/
Copy pathreverse-inner-string.js
File metadata and controls
69 lines (60 loc) · 2.21 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
58
59
60
61
62
63
64
65
66
67
68
69
/**
* keep open variable, replace it with the index of each open paren you find
* when hit a closed paren, reverse the substring and splice it into the main string
* keep calling revSplice until open === 0 at the end of loop
*
* Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
Example
For inputString = "(bar)", the output should be
solution(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
solution(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be
solution(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be
solution(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".
Input/Output
[execution time limit] 4 seconds (js)
[input] string inputString
A string consisting of lowercase English letters and the characters ( and ). It is guaranteed that all parentheses in inputString form a regular bracket sequence.
Guaranteed constraints:
0 ≤ inputString.length ≤ 50.
[output] string
Return inputString, with all the characters that were in parentheses reversed.
*/
function solution(inputString) {
function revSplice(open, close, input) {
let reversed = '';
for (let i = close - 1; i >= open + 1; i--) {
reversed = reversed + input[i];
}
let fixedString = '';
if (open > 0) {
fixedString = input.slice(0, open);
}
fixedString = fixedString + reversed;
if (close < input.length - 1) {
fixedString = fixedString + input.slice(close + 1, input.length);
}
return fixedString;
}
let open = null;
let closed = null;
for (let i = 0; i < inputString.length; i++) {
if (inputString[i] === '(') {
open = i;
}
if (inputString[i] === ')') {
closed = i;
inputString = revSplice(open, closed, inputString);
//console.log(`INSIDE=== i=${i}, inputSTring=${inputString}, open=${open}, closed=${closed}`);
i = -1;
open = null;
closed = null;
}
//console.log(`i=${i}, inputSTring=${inputString}, open=${open}, closed=${closed}`);
}
return inputString;
}