Problem: The type of (()) () () () () ()) (()) replaced by [][][[[]][]], which handles parentheses
Author: infinte
Requirements:
[1] supports arbitrary "brackets", which means "<>{}" () ... or XML-like:<a></a>, [Cc][cc:over], {TTT] [TTT}
[2] strictly in accordance with the hierarchy, that is (a) B (c (d) e) replaced by [a]b[c[d]e] rather than [A]b[c (d]e) (end too early)
[3] The opening parenthesis is more than the right parenthesis and retains the extra brackets, namely: () () (() ()) (() ()) →[][] [[[]]
[4] The closing parenthesis is more than the left parenthesis, leaving the extra brackets, i.e. (() () (() ()))))))
Scenario One: Using stacks
Author: Winter
Code:
Copy Code code as follows:
<script>
var Strarr = "() () ((() ())";
function Change (str)
{
var a=str.split ("");
var c=0;
var stack=[];
var match={
"(":")",
"{":"}",
"<": ">",
"【":"】"
}
for (Var i=0;i<a.length;i++)
if (Match[a[i]]) {
Stack.push ([a[i],i]);
}
else if (a[i]== ")" | | a[i]== "}" | | a[i]== ">" | | a[i]== "" ") {
if (!stack.length) continue;
var tmp=stack.pop ();
if (Match[tmp[0]]==a[i]) a[i]= "]", a[tmp[1]]= "[";
else Stack.push (TMP);
}
Return A.join ("");
}
Alert (change (Strarr));
</script>
Programme II: Use of regular
Author: Moon Shadow
Code:
Copy Code code as follows:
<script>
var strarr = " () () ((()) ";
var o = strarr;
var r = o;
do{
o ;= r;
r = o.replace (/\ ([^ ()]*) \)/g,function (s,a) {return ' [' +a+ '] '});
}while (o!=r);
Alert (r);
</script>